Scala: Boolean to Option

前端 未结 10 1764
一整个雨季
一整个雨季 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:36

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

    myBool.option(someResult)
    

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

    implicit class RichBoolean(val b: Boolean) extends AnyVal {
      final def option[A](a: => A): Option[A] = if (b) Some(a) else None
    }
    
    0 讨论(0)
  • 2021-02-02 05:37
    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
    
    0 讨论(0)
  • 2021-02-02 05:38

    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
    
    0 讨论(0)
  • 2021-02-02 05:43

    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") { ... }
    
    0 讨论(0)
  • 2021-02-02 05:44

    Starting Scala 2.13, Option has a when builder for this exact purpose:

    Option.when(condition)(result)
    

    For instance:

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

    Also note Option.unless which promotes the opposite condition.

    0 讨论(0)
  • 2021-02-02 05:48
    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 condOpt is the value returned if the guard evaluates to true.

    0 讨论(0)
提交回复
热议问题