[英]How to transform Option[A] to Either[String, B] in Scala with Cats?
I create small code samples where want to show how cats library work. 我在希望显示cats库如何工作的地方创建了小的代码示例。 While I was working on the last one example, I noticed that it probably could be more elegant: 当我处理最后一个示例时,我注意到它可能更优雅:
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
What is a way to rewrite the code snippet in a more concise form using cats syntax? 使用cats语法以更简洁的形式重写代码段的方法是什么?
You don't need to create another IO, as the expression in yield result will be already wrapped by IO by the for comprehension. 您无需创建另一个IO,因为yield表达式中的表达式已经由IO进行了包装,以进行理解。
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
Or even 甚至
def deleteWord(id: Int): IO[Either[String, Unit]] =
for (removedWord <- IO(storage.remove(id)))
yield removedWord.map(_=>()).toRight(s"Word with $id not found")
Maybe you oversimplified your sample, but Cats will not improve such transformation 也许您简化了样本,但是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")
One of the solutions which I received in gitter cats 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
it seems exactly what I needed 似乎正是我所需要的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.