Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

scala

This common pattern feels a bit verbose:

if (condition) 
  Some(result)
else None

I was thinking of using a function to simplify:

def on[A](cond: Boolean)(f: => A) = if (cond) Some(f) else None

This reduces the top example to:

on (condition) { result }

Does something like this exist already? Or is this overkill?

like image 911
Tim Avatar asked Oct 04 '12 13:10

Tim


4 Answers

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)
like image 179
drexin Avatar answered Oct 19 '22 12:10

drexin


Scalaz includes the option function:

import scalaz.syntax.std.boolean._

true.option("foo") // Some("foo")
false.option("bar") // None
like image 37
Ben James Avatar answered Oct 19 '22 11:10

Ben James


Starting Scala 2.13, Option is now provided with the when builder which does just that:

Option.when(condition)(result)

For instance:

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

Also note the coupled unless method which does the opposite.

like image 19
Xavier Guihot Avatar answered Oct 19 '22 11:10

Xavier Guihot


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)
like image 4
Nicolas Avatar answered Oct 19 '22 13:10

Nicolas