Using Either to process failures in Scala code

后端 未结 4 896
陌清茗
陌清茗 2020-11-28 03:27

Option monad is a great expressive way to deal with something-or-nothing things in Scala. But what if one needs to log a message when \"nothing\" occurs? Accord

4条回答
  •  一个人的身影
    2020-11-28 03:42

    Cats has a nice way to create an Either from exception-throwing code:

    val either: Either[NumberFormatException, Int] =
      Either.catchOnly[NumberFormatException]("abc".toInt)
    // either: Either[NumberFormatException,Int] = Left(java.lang.NumberFormatException: For input string: "abc")
    

    in https://typelevel.org/cats/datatypes/either.html#working-with-exception-y-code

提交回复
热议问题