スカラ関数が
def A(): Either[Exception, ArrayBuffer[Int]] = {
...
}
返された結果を処理する正しい方法は何ですか?
val a = A()
と ?
私は一般的に使用することを好みfold
ます。マップのように使用できます:
scala> def a: Either[Exception,String] = Right("On")
a.fold(l => Left(l), r => Right(r.length))
res0: Product with Either[Exception,Int] = Right(2)
または、パターン マッチのように使用できます。
scala> a.fold( l => {
| println("This was bad")
| }, r => {
| println("Hurray! " + r)
| })
Hurray! On
getOrElse
または、次のように使用できますOption
。
scala> a.fold( l => "Default" , r => r )
res2: String = On
最も簡単な方法は、パターン マッチングを使用することです
val a = A()
a match{
case Left(exception) => // do something with the exception
case Right(arrayBuffer) => // do something with the arrayBuffer
}
あるいは、Either にはさまざまなかなり単純な方法があり、それらをジョブに使用できます。これがscaladoc http://www.scala-lang.org/api/current/index.html#scala.Eitherです
一つの方法は
val a = A();
for (x <- a.left) {
println("left: " + x)
}
for (x <- a.right) {
println("right: " + x)
}
for 式の本体の 1 つだけが実際に評価されます。