I'm searching for a possiblity in scala to call a function and get an Option
as result which is "None" iff either an Exception is raised when calling the method or the method return null. Otherwise the Option should have the value of the result.
I know that Try
can be used for the first part, but I don't know how to handle the second part:
val result = Try(myFunction).toOption()
If the method now returns null (because it is not a scala function but a Java function), result
is Some(null)
instead of None
.
In Scala, using null to represent nullable or missing values is an anti-pattern: use the type Option instead. The type Option ensures that you deal with both the presence and the absence of an element. Thanks to the Option type, you can make your system safer by avoiding nasty NullPointerException s at runtime.
Null is - together with scala. Nothing - at the bottom of the Scala type hierarchy. Null is the type of the null literal. It is a subtype of every type except those of value classes.
An Option[T] can be either Some[T] or None object, which represents a missing value. For instance, the get method of Scala's Map produces Some(value) if a value corresponding to a given key has been found, or None if the given key is not defined in the Map.
As I know there is only 1 method in scala standard library to convert null
to None
- Option.apply(x)
, so you have to use it manually:
val result = Try(myFunction).toOption.flatMap{Option(_)}
// or
val result = Try(Option(myFunction)).toOption.flatten
You could create your own helper method like this:
implicit class NotNullOption[T](val t: Try[T]) extends AnyVal {
def toNotNullOption = t.toOption.flatMap{Option(_)}
}
scala> Try(null: String).toNotNullOption
res0: Option[String] = None
scala> Try("a").toNotNullOption
res1: Option[String] = Some(a)
You can also do this:
val result = Try(myFunction).toOption.filter(_ != null)
which looks and feels better then .flatten
or .flatMap(Option(_))
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