質問

このように、Scalaでいくつかのオプションの1つの値を取得したいです。

def or(a:Option[Int], b:Option[Int]):Option[Int]=
    if (a.isDefined) a else b

val a= Option(1)
val b= Option(2)
or(a,b).get
.

しかし、||演算子がオプションのために定義されていないのはなぜだろうか?これを行う慣性的な方法はありますか?

役に立ちましたか?

解決

Orelseを使用してください。

scala> Some(1) orElse Some(2)
res0: Option[Int] = Some(1)

scala> (None: Option[Int]) orElse Some(2)
res1: Option[Int] = Some(2)
.

他のヒント

Scalaz 7を使用すると、Tags.First Monoid:

を使用できます。
[info] Starting scala interpreter...
[info] 
import scalaz._
import Scalaz._
Welcome to Scala version 2.10.3 (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_51).
Type in expressions to have them evaluated.
Type :help for more information.

scala> Tags.First('a'.some) |+| Tags.First('b'.some)
res0: scalaz.@@[Option[Char],scalaz.Tags.First] = Some(a)

scala> Tags.First(none[Char]) |+| Tags.First('b'.some)
res1: scalaz.@@[Option[Char],scalaz.Tags.First] = Some(b)

scala> Tags.First('a'.some) |+| Tags.First(none[Char])
res2: scalaz.@@[Option[Char],scalaz.Tags.First] = Some(a)
.

オプション

orElseを使用します。

val a = None
val b = Some("b")

a orElse b
.

いくつか( "b")

を返します

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top