Scala:布尔到选项 [英] Scala: Boolean to Option
本文介绍了Scala:布尔到选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个布尔值并且想避免这种模式:
I have a Boolean and would like to avoid this pattern:
if (myBool)
Option(someResult)
else
None
我想做的是
myBool.toOption(someResult)
对代码示例的任何建议将不胜感激.
Any suggestions with a code example would be much appreciated.
推荐答案
从 Scala 2.13
开始,Option
有一个 when
用于此确切目的的构建器:
Starting Scala 2.13
, Option
has a when
builder for this exact purpose:
Option.when(condition)(result)
例如:
Option.when(true)(3)
// Option[Int] = Some(3)
Option.when(false)(3)
// Option[Int] = None
另请注意 Option.unless
促进相反的条件.
Also note Option.unless
which promotes the opposite condition.
这篇关于Scala:布尔到选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文