Search code examples
scalascala-cats

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. 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?


Solution

  • 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