Option类有一个很好的方法foreach
,如果指定了value,它会调用传递的代码。 None
价值是否有类似的技术?我知道.orElse
方法,但是,使用它,我需要从代码块返回Option
:
x orElse {
// do something
None // <-- I want to avoid this line
}
答案 0 :(得分:4)
如果你想在None
案件中做点什么我认为你是副作用的。那有什么不对:
if(o.isEmpty){
// do things
}
答案 1 :(得分:2)
我不认为它存在于标准选项库中,但您可以使用隐式类
添加它class OptionFunctions[T](val opt: Option[T]) extends AnyVal {
def ifEmpty[A](f: => A): Unit = {
if (opt.isEmpty) f
}
}
并像这样使用它:
val o = Some(1)
o.ifEmpty { println("empty") }
答案 2 :(得分:1)
模式匹配可能吗?
option match {
case Some(foo) => println("Have " + foo)
case None => println("Have nothing.")
}