次のように、scala でいくつかの Option のいずれかの値を取得したい:
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
しかし、なぜ||
Option の演算子が定義されていないのだろうか? これを行うためのより慣用的な方法はありますか?
次のように、scala でいくつかの Option のいずれかの値を取得したい:
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
しかし、なぜ||
Option の演算子が定義されていないのだろうか? これを行うためのより慣用的な方法はありますか?
Scalaz 7 を使用すると、Tags.First
モノイドを使用できます。
[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
Some("b") を返します