开发者

Which Scala methods return null instead of an Option and why?

I wonder if the standard library is completely null-free and - if not 开发者_高级运维- would be interested what reasonable use-cases exist where returning null is preferable to returning some Option instance.


NamespaceBinding returns null for the local namespace or in the following case an undefined input.

$ scala
Welcome to Scala version 2.9.0.1 (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_24).
Type in expressions to have them evaluated.
Type :help for more information.

scala> (<foo/>).scope.getURI("something")
res0: String = null

Why it's using String instead of Option[URI], I don't know.


The only place I've seen null used in the standard library are optional regex groups.

scala> val number = """(\d+)(\.\d+)?""".r // matches digits optionally followed by a . and more digits
number: scala.util.matching.Regex = (\d+)(\.\d+)?
scala> "12" match {
     |   case number(intPart, decimalPart) => (intPart, decimalPart)
     | }
res0: (String, String) = (12,null)

I think, the reasoning here is that you don't want to use Option[String] for all groups. This would make the code unnecessarily clumsy, if a group is not optional. Unfortunately, it is not known at compile time if a group is optional. So it's either Option[String] for all groups or null for not matching groups.


I can't think of any so I did a google search in the api (inurl:scala-lang.org/api return +null) and it didn't seem to yield any documented use of null.

May be there exist som internal use. The only reasons I can think of for doing that would be to avoid the extra Some-object or to easy integration with java. Both seem unlikely.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜