Shouichi
Shouichi

Reputation: 1150

Convert a condition to Option in Scala

I want do something like this.

if (x > 0) {
  Some(123)
} else {
  None
}

The shorter way would be the following.

Try(x > 0).toOption.map(_ => 123)

It seems little bit unnatural for me to use Try (which is designed to catch exceptions) for checking a condition. Are there other ways of accomplishing this?

Edit:

Try doesn't work because x > 0 doesn't throw an exception when x is negative.

Upvotes: 4

Views: 4381

Answers (2)

Xavier Guihot
Xavier Guihot

Reputation: 61666

Starting Scala 2.13, Option is provided with the method when, which produces Some(a) if a matches the condition and None otherwise:

// val x = 45
Option.when(x > 0)(x)
// Option[Int] = Some(45)

// val x = -6
Option.when(x > 0)(x)
// Option[Int] = None

// val x = 45
Option.when(x > 0)(123)
// Option[Int] = Some(123)

Upvotes: 24

chengpohi
chengpohi

Reputation: 14217

Some(x).filter(_ > 0).map(_ => 123)

With Option you can use filter and map.

Upvotes: 7

Related Questions