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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With