Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 457
soc Avatar asked May 30 '11 21:05

soc


2 Answers

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.

like image 126
Eugene Yokota Avatar answered Oct 28 '22 10:10

Eugene Yokota


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.

like image 41
kassens Avatar answered Oct 28 '22 11:10

kassens