【问题标题】:How to transform Option[A] to Either[String, B] in Scala with Cats?如何在 Scala 中使用 Cats 将 Option[A] 转换为 Either[String, B]?
【发布时间】:2019-08-29 18:37:36
【问题描述】:

我创建了一些小代码示例来展示猫库的工作原理。在处理最后一个示例时,我注意到它可能更优雅:

import cats.effect.IO
import scala.collection.mutable.HashMap

val storage = HashMap[Int, String]().empty

override def deleteWord(id: Int): IO[Either[String, Unit]] =
  for {
    removedWord <- IO(storage.remove(id))
    result <- IO {
                removedWord.flatMap(_ => Some(())).toRight(s"Word with $id not found")
              }
  } yield result

有什么方法可以用cats语法以更简洁的形式重写代码sn-p?

【问题讨论】:

    标签: scala scala-cats


    【解决方案1】:

    我在 gitter cat chat 中收到的一个解决方案:

    import cats.implicits._
    
    override def deleteWord(id: Int): IO[Either[String, Unit]] =
      for {
        removedWord <- IO(storage.remove(id))
        result <- IO(removedWord.toRight(s"Word with $id not found").void)
      } yield result
    

    这似乎正是我所需要的

    【讨论】:

      【解决方案2】:

      您不需要创建另一个 IO,因为 yield result 中的表达式已经被 IO 通过 for 理解包装了。

      def deleteWord(id: Int): IO[Either[String, Unit]] =
        for {
          removedWord <- IO(storage.remove(id))
          result = removedWord.map(_=>()).toRight(s"Word with $id not found")
        } yield result
      

      甚至

      def deleteWord(id: Int): IO[Either[String, Unit]] =
        for (removedWord <- IO(storage.remove(id)))
          yield removedWord.map(_=>()).toRight(s"Word with $id not found")
      

      【讨论】:

        【解决方案3】:

        也许你过度简化了你的样本,但 Cats 不会改进这种转换

        import scala.collection.mutable.HashMap
        import cats.implicits._
        
        val storage = HashMap(1 -> "abc")
        
        def deleteWord(id: Int) =
          storage
            .remove(id)
            .fold(s"Word with $id not found".asLeft[Unit])(_ => ().asRight)
        
        deleteWord(1)
        // Either[String, Unit] = Right(())
        deleteWord(2)
        // Either[String, Unit] = Left("Word with 2 not found")
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-12-08
          • 2019-09-23
          • 1970-01-01
          • 1970-01-01
          • 2016-04-14
          • 2019-10-23
          • 2012-02-08
          相关资源
          最近更新 更多