0

When Scala app interacting with Java code it sometimes need to handle null returned by Java method.

Which of this 2 ways is more scala idiomatic? Which one should I use?

1.

val a = javaClass.javaMethod
if (a == null) 
  throw new IllegalArgumentException("Wrong param")
processA(a)

2.

val a = Option(javaClass.javaMethod)
processA(a.getOrElse(throw new IllegalArgumentException("Wrong param")))
WelcomeTo
  • 19,843
  • 53
  • 170
  • 286
  • 4
    There isn't much of a point in wrapping it with `Option` only to use `getOrElse` and throw an exception anyway. What do you plan on doing with it? – Michael Zajac Apr 13 '15 at 19:52
  • Method 2 has the advantage of allowing you to perform a pattern-match. – Owen Apr 13 '15 at 19:54
  • @m-z variable `a` will not be used in pattern matching etc. I just need to be sure that is not `null`, and if it's `null` I consider it as exceptional situation and no need to proceed method execution – WelcomeTo Apr 13 '15 at 19:56
  • 5
    If you just want to throw an exception you can use `require(a != null, "Wrong param")` – Lee Apr 13 '15 at 20:06

2 Answers2

3

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.

Rex Kerr
  • 166,841
  • 26
  • 322
  • 407
0

I prefer 1st solution, which is clearer than 2nd one.

And it can be refined to Scala idiom:

require(a != null, "Wrong param")

Option is not proper in this case, because Option is usually designed in a returned value. For example, List.find(...): Option.

卢声远 Shengyuan Lu
  • 31,208
  • 22
  • 85
  • 130