I know in Scala a method should never return null… but what’s about input parameters? Given the following code snippet…
object MyObject {
def myMethod(p: String): Option[String] = {
if (p == null) throw new IllegalArgumentException("p is null.")
...
}
}
… is the way I check p correct? Is there any recommendation?
The convention is that Scala code does not use nulls (with a tiny number of exceptions, which should immediately be fixed when using those library functions).
Thus, a null from Scala is a sign that something has gone wrong (at least a PBCAK), so you may as well throw an exception. This is not routine operation; this is something seriously screwed up. Catch the exception wherever you catch serious screw-ups. Catching an
IllegalArgumentExceptioninstead of aNullPointerExceptionadds no extra information. Just leave the original alone.If the code comes from Java, the canonical way of dealing with it is to wrap it in
Option, which will convertnulltoNone. Then you probably don’t even need to throw an exception; just return aNone.If you cannot continue when it is null, then you need to consider whether an informative exception would help.
Option(p).orElse(throw new IllegalArgumentException("Null!"))is one compact way of expressing the exception-throwing sentiment.In Scala 2.10, you can also wrap things in
scala.util.Try(...)which will automatically catch and package the exception for you. If you want a packaged exception instead of a thrown one, this is the way to go. (And useTryinstead ofOption.)Finally, for more general handling of alternative outcomes, use
Either. The convention for error handling is that the expected output is aRight(whatever), whileLeft(whatever)indicates that something went wrong.