Scala - "if(true) Some(1)" without having to type "else None"

If you don't mind creating the data every time,

Some(data).filter(someCondition)

will do the trick. If you do mind creating the data every time,

Option(someCondition).filter(_ == true).map(_ => data)

but I don't think that's any clearer. I'd go with if-else if I were you.

Or you could

def onlyIf[A](p: Boolean)(a: => A) = if (p) Some(a) else None

and then

onlyIf(someCondition){ data }

Scalaz has this. The code would look like this:

import scalaz._
import Scalaz._
val b = true  
val opt = b option "foo"

The type of opt will be Option[String]


How about playing with the fire:

implicit class CondOpt[T](x: => T) {
  def someIf(cond: Boolean) = if (cond) Some(x) else None
}

Use:

data someIf someCondition

Drawbacks:

  1. Dangerous, implicit conversion from Any
  2. Calculates data every time

Tags:

Scala