Scala: Boolean to Option

前端 未结 10 1745
一整个雨季
一整个雨季 2021-02-02 05:30

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

if (myBool) 
  Option(someResult) 
else 
  None

What I\'d like to do is



        
相关标签:
10条回答
  • 2021-02-02 05:49
    Option(true).find(_ == true) // Some(true)
    Option(false).find(_ == true) // None
    
    0 讨论(0)
  • 2021-02-02 05:50

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

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

    from the REPL:

    scala> (Option(true).collect { case true => 3 }, Option(false).collect { case true => 3 })
    res3: (Option[Int], Option[Int]) = (Some(3),None)
    
    0 讨论(0)
  • 2021-02-02 05:50

    If you don't mind someResult being evaluated no matter the value of myBool you can also use

    Some(someResult).filter(myBool)
    
    0 讨论(0)
  • 2021-02-02 06:02

    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
    
    0 讨论(0)
提交回复
热议问题