theomega
theomega

Reputation: 32031

Try / Option with null

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.

Upvotes: 13

Views: 6206

Answers (3)

Roberto_ua
Roberto_ua

Reputation: 41

You can also do this:

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

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

Upvotes: 4

senia
senia

Reputation: 38045

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)

Upvotes: 24

e.tomeo
e.tomeo

Reputation: 11

You can also do pattern matching as:

val result = myFunction() match {
   case null => None
   case _    => Some(_)
}

but the answer of @senia looks more "scala style"

Upvotes: 0

Related Questions