Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try / Option with null

Tags:

scala

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.

like image 647
theomega Avatar asked Jan 20 '14 10:01

theomega


People also ask

Can options be null Scala?

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.

Does Scala have null?

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.

What are option some and none in Scala?

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.


2 Answers

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)
like image 116
senia Avatar answered Oct 21 '22 08:10

senia


You can also do this:

val result = Try(myFunction).toOption.filter(_ != null)

which looks and feels better then .flatten or .flatMap(Option(_))

like image 32
Roberto_ua Avatar answered Oct 21 '22 07:10

Roberto_ua