Wrapping null-returning method in Java with Option in Scala?

José Leal picture José Leal · Jan 14, 2011 · Viewed 37.4k times · Source

Suppose I have a method session.get(str: String): String but you don't know whether it will return you a string or a null, because it comes from Java.

Is there an easier way to treat this in Scala instead of session.get("foo") == null ? Maybe some magic apply like ToOption(session.get("foo")) and then I can treat it in Scala way like

ToOption(session.get("foo")) match {
    case Some(_) =>;
    case None =>;
}

Answer

Tom Crockett picture Tom Crockett · Jan 14, 2011

The Option companion object's apply method serves as a conversion function from nullable references:

scala> Option(null)
res4: Option[Null] = None

scala> Option(3)   
res5: Option[Int] = Some(3)