Simplify if (x) Some(y) else None?

后端 未结 7 1884
旧时难觅i
旧时难觅i 2021-02-05 02:46

This common pattern feels a bit verbose:

if (condition) 
  Some(result)
else None

I was thinking of using a function to simplify:



        
相关标签:
7条回答
  • 2021-02-05 03:05

    Scalaz includes the option function:

    import scalaz.syntax.std.boolean._
    
    true.option("foo") // Some("foo")
    false.option("bar") // None
    
    0 讨论(0)
  • 2021-02-05 03:13

    You can use the PartialFunction companion object and condOpt:

    PartialFunction.condOpt(condition) {case true => result}
    

    Usage:

     scala> PartialFunction.condOpt(false) {case true => 42}
     res0: Option[Int] = None
    
     scala> PartialFunction.condOpt(true) {case true => 42}
     res1: Option[Int] = Some(42)
    
    0 讨论(0)
  • 2021-02-05 03:17

    Similar to Scalaz, the Typelevel cats ecosystem has the mouse package with option:

    scala> true.option("Its true!")
    res0: Option[String] = Some(Its true!)
    
    0 讨论(0)
  • 2021-02-05 03:21

    You could create the Option first and filter on that with your condition:

    Option(result).filter(condition)
    

    or if condition is not related to result

    Option(result).filter(_ => condition)
    
    0 讨论(0)
  • 2021-02-05 03:22
    import scalaz._, Scalaz._
    val r = (1 == 2) ? Some(f) | None
    System.out.println("Res = " + r)
    
    0 讨论(0)
  • 2021-02-05 03:23

    Here is another approach that is quite straightforward:

    Option(condition).collect{ case true => result }
    

    A simple example:

    scala> val enable = true
    enable: Boolean = true
    
    scala> Option(enable).collect{case true => "Yeah"}
    res0: Option[String] = Some(Yeah)
    
    scala> Option(!enable).collect{case true => "Yeah"}
    res1: Option[String] = None
    

    Here some advanced non-Boolean examples that put the condition into the pattern match:

    val param = "beta"
    Option(param).collect{case "alpha" => "first"} // gives None
    
    Option(param).collect{case "alpha" => "first"
                          case "beta"  => "second"
                          case "gamma" => "third"} // gives Some(second)
    
    val number = 999
    Option(number).collect{case 0 => "zero"
                           case x if x > 10 => "too high"} // gives Some(too high)
    
    0 讨论(0)
提交回复
热议问题