by shigemk2

当面は技術的なことしか書かない

ScalaのEither型 Left vs Right

Eitherによるエラー処理 - エラー処理による分岐を減らす | Scala Cookbook

Right型の場合はmap内の関数を適用し、Leftの型の場合はmapの処理を無視してLeftの内容(この場合はエラー情報を)をそのまま返す。

環境は、Mac OSXと、2.10.3

scala> def parseInt(s:String) : Either[Exception, Int] =
     | try Right(s.toInt) catch { case e:Exception => Left(e) }
parseInt: (s: String)Either[Exception,Int]

scala> parseInt("128")
res0: Either[Exception,Int] = Right(128)

scala> parseInt("234A")
res1: Either[Exception,Int] = Left(java.lang.NumberFormatException: For input string: "234A")

scala> parseInt("49").right map { _.toFloat }
res2: Product with Serializable with scala.util.Either[Exception,Float] = Right(49.0)

scala> parseInt("ADF").right map { _.toFloat }
res3: Product with Serializable with scala.util.Either[Exception,Float] = Left(java.lang.NumberFormatException: For input string: "ADF")

scala> parseInt("ADF").left map { _.getMessage }
res4: Product with Serializable with scala.util.Either[String,Int] = Left(For input string: "ADF")

scala> parseInt("40").left map { _.getMessage }
res5: Product with Serializable with scala.util.Either[String,Int] = Right(40)