0

Given the following method,

scala> def f(x: Option[String]): Either[String, Int] = x match {
        case Some(x) => try { Right(x.toInt) } 
                        catch { 
                          case _:  NumberFormatException => Left(s"Not an int: $x") 
                        }
        case None    => Left("No String present.")
      }
f: (x: Option[String])Either[String,Int]

testing

scala> f(None)
res0: Either[String,Int] = Left(No String present.)

scala> f(Some("44"))
res2: Either[String,Int] = Right(44)

scala> f(Some("zipp"))
res3: Either[String,Int] = Left(Not an int: zipp)

How would a Monad transformer be used here?

Note - I don't know if it's a good example since it's so short (and the pattern match might be the cleanest way), but I'm curious anyway.

Kevin Meredith
  • 41,036
  • 63
  • 209
  • 384

0 Answers0