The convention is that Scala code does not use NULL values ββ(with a few exceptions that should be fixed immediately when using these library functions).
So zero from Scala is a sign that something went wrong (at least PBCAK ), so you can also throw an exception, This is not an ordinary operation; it is something serious. Catch the exception wherever you find serious disgust. Capturing IllegalArgumentException instead of NullPointerException does not add additional information. Just leave the original alone.
If the code comes from Java, the canonical way to deal with it is to wrap it in Option , which converts null to None . Then you probably don't even need to throw an exception; just return a None .
def myMethod(p: String) = Option(p).map(_.toLowerCase)
If you cannot continue when it is null, you need to think about whether an informative exception will help. Option(p).orElse(throw new IllegalArgumentException("Null!")) Is one compact way to express emotions that create an exception.
In Scala 2.10, you can also wrap things in scala.util.Try(...) , which will automatically catch and pack an exception for you. If you want a packed exception instead of a thrown, this is the way to go. (And use Try instead of Option .)
import scala.util.Try def myMethod(p: String) = Try(p.toLowerCase)
Finally, for more general handling of alternative results, use Either . The convention for error handling is that the expected result is Right(whatever) , and Left(whatever) indicates that something went wrong.
Rex kerr
source share