Scala:布尔到选项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19690531/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 05:48:53  来源:igfitidea点击:

Scala: Boolean to Option

scala

提问by Chris Beach

I have a Boolean and would like to avoid this pattern:

我有一个布尔值,想避免这种模式:

if (myBool) 
  Option(someResult) 
else 
  None

What I'd like to do is

我想做的是

myBool.toOption(someResult)

Any suggestions with a code example would be much appreciated.

任何有关代码示例的建议将不胜感激。

采纳答案by Xavier Guihot

Starting Scala 2.13, Optionhas a whenbuilder for this exact purpose:

开始Scala 2.13,Option具有when用于此确切目的的构建器:

Option.when(condition)(result)

For instance:

例如:

Option.when(true)(3)
// Option[Int] = Some(3)
Option.when(false)(3)
// Option[Int] = None

Also note Option.unlesswhich promotes the opposite condition.

还要注意Option.unless哪个促进了相反的条件。

回答by n1r3

Scalaz has a way to do it with BooleanOps.option. That would allow you to write :

Scalaz 有一种方法可以使用BooleanOps.option来做到这一点。这将允许你写:

myBool.option(someResult)

If you don't want to add a Scalaz dependency, just add the following in your code :

如果您不想添加 Scalaz 依赖项,只需在代码中添加以下内容:

implicit class RichBoolean(val b: Boolean) extends AnyVal {
  final def option[A](a: => A): Option[A] = if (b) Some(a) else None
}

回答by Brian O'Clair

Option().collect() is a good pattern for this kind of thing.

Option().collect() 是处理这类事情的好模式。

Option(myBool).collect { case true => someResult }

from the REPL:

来自 REPL:

scala> (Option(true).collect { case true => 3 }, Option(false).collect { case true => 3 })
res3: (Option[Int], Option[Int]) = (Some(3),None)

回答by jazmit

None of the other answers answer the question as stated! To get the exact semantics you specified use:

其他答案都没有回答所述问题!要获得您指定的确切语义,请使用:

implicit class BoolToOption(val self: Boolean) extends AnyVal {
  def toOption[A](value: => A): Option[A] =
    if (self) Some(value) else None
}

You can then write

然后你可以写

myBool.toOption(someResult)

eg:

例如:

scala> true.toOption("hi")
res5: Option[String] = Some(hi)

scala> false.toOption("hi")
res6: Option[String] = None

回答by jazmit

If you don't mind someResultbeing evaluated no matter the value of myBoolyou can also use

如果你不介意someResult被评价不管myBool你的价值你也可以使用

Some(someResult).filter(myBool)

回答by J Cracknell

Another choice:

另一种选择:

implicit class RichOptionCompanion(val self: Option.type) extends AnyVal {
  def when[A](cond: Boolean)(value: => A): Option[A] = if(cond) Some(value) else None
}

Usage:

用法:

Option.when(foo != "bar") { ... }

回答by kiritsuku

scala> PartialFunction.condOpt(5) { case x if true => x }
res9: Option[Int] = Some(5)

scala> PartialFunction.condOpt(5) { case x if false => x }
res10: Option[Int] = None

Here, the guard holds the condition and the value passed to condOptis the value returned if the guard evaluates to true.

这里,守卫保存条件,传递给condOpt的值是当守卫评估为真时返回的值。

回答by flavian

class RichBool[T](a: Boolean, res:=> T) {
   def toOption: Option[T] = if (a) Some(res) else None
}
implicit def boolToRichBool[T](tp: (Boolean, T)): RichBool[T] = new RichBool(tp._1, tp._2);

This would give you:

这会给你:

(true, 5).toOption // Some(5);
(false, 3).toOption // None

回答by Joe

Here are a couple things I would consider:

我会考虑以下几点:

val bool: Boolean = ???
val result = 1337    

Option(bool).withFilter(identity).map(_ => result)

or

或者

for {
  opt <- Option(bool)
  if opt
} yield result

回答by Gal Morad

Option(true).find(_ == true) // Some(true)
Option(false).find(_ == true) // None