returning method in Java with Option in Scala?

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

Option伴侣对象的apply方法充当可空引用的转换函数:

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

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

Option对象具有一个apply方法,它完全符合:

var myOptionalString = Option(session.get("foo"));
链接地址: http://www.djcxy.com/p/86192.html

上一篇: 获得斯卡拉列表中的项目?

下一篇: Java中带有Option的Scala中返回方法?