Alex Rivera | Logout

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

Asked 2011-01-14T15:13:31.397
123

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 =>;
}
Edit
Report

1 Answer

20

The Option object has an applymethod that does exactly that:

var myOptionalString = Option(session.get("foo"));
answered 2011-01-14T15:23:39.280

Your Answer