Scala is forced to have a "null" value because it interoperates with Java. However unlike Java APIs the recommended way to hand cases where there may or may not be a value (IE a return value) is to return an Option object. Compare the Scala and Java idioms for handling a possible null (or None) return value:
Note: The Option class have been updated in Scala 2.8 so I am going to use some of the scala 2.8 methods. Most of the examples will work with Scala 2.7 but not all; the principal is the same for 2.7 and 2.8.
Java:
- /**
- * Returns the annotation with the given name or null if there is no annotation
- * on the objects class with the given name.
- */
- public static < A extends java.lang.annotation.Annotation> Annotation annotation(Object obj, Class< A> annotationCls) {
- return obj.getClass().getAnnotation(annotationCls)
- }
Scala:
- import java.lang.annotation.Annotation
- /**
- * Returns the annotation with the given name.
- */
- def annotation[A <: Annotation](obj:Object, annotationCls:Class[A]) : Option[Annotation] = {
- Option (obj.getClass.getAnnotation (annotationCls))
- }
In the Scala version it is obvious the use of the API (and the compiler) that there are two types of legal return types. Some or None and the compiler will force you to deal with this fact. Where in Java it is very easy to forget to check for null.
Also not that it is very easy to Wrap a null in an Option using the Option objects apply method. If the parameter is a null then None is return otherwise Some is returned.
The other important aspect is how to deal with the Option object and obtain the data from the object if it is present. This is both simple and non-simple. There are a large number of possible useage patterns that can be applied to it.
Examples: