If it is an advantage to defer deciding what to do about null
, then you should use the Option
form because it forces you to deal with it later (i.e. you can't forget).
Otherwise, if you're going to throw an exception anyway, you should just do it as fast as possible, without introducing any superfluous variables. Using an if
statement is a fine way to do it if you were going to write a
anyway. If not, you might want to write a helper extension method:
implicit class ThrowExceptionOnNull[A](private val underlying: A) extends AnyVal {
def throwIfNull(msg: String = "Wrong param") = {
if (underlying == null) throw new IllegalArgumentException(s)
underlying
}
}
Then your code doesn't even need the temporary a
variable:
processA(javaClass.javaMethod.throwIfNull)
and the method name is a pretty good warning to whoever is reading the code about what will happen if it's null.
Option(javaClass.javaMethod).get
will also throw an exception and is built in, but it's inelegant. That's not what Option
is supposed to be for, so you're better off writing your own method.