Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a condition to Option in Scala

Tags:

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.

like image 284
Shouichi Avatar asked Oct 26 '25 21:10

Shouichi


1 Answers

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)
like image 149
Xavier Guihot Avatar answered Oct 29 '25 11:10

Xavier Guihot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!