soc
soc

Reputation: 28423

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.

Upvotes: 11

Views: 763

Answers (3)

Eugene Yokota
Eugene Yokota

Reputation: 95604

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.

Upvotes: 5

kassens
kassens

Reputation: 4475

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.

Upvotes: 5

thoredge
thoredge

Reputation: 12591

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.

Upvotes: -1

Related Questions