Kevin Meredith
Kevin Meredith

Reputation: 41909

Passing in `null` to Option[Int] Argument

I have a function foo:

scala> def foo(maybeInt: Option[Int]) = maybeInt.map(_ + 5)
foo: (maybeInt: Option[Int])Option[Int]

scala> foo(Some(5))
res10: Option[Int] = Some(10)

However, I can pass in null to get a NPE:

scala> foo(null)
java.lang.NullPointerException
      ...

At compile-time, is there any way to avoid this error? Or are null checks simply required in Scala?

I would strongly expect the above code to fail a code review, yet I'd want the compiler to catch it.

Upvotes: 0

Views: 1153

Answers (2)

Daniel C. Sobral
Daniel C. Sobral

Reputation: 297195

I think you can avoid it by using overload. If you add a foo method taking Null it should take precedence. It will still compile, though, so you have to add something else. I'd try an non-existent implicit. Something like this:

def foo(m: Option[Int]): Option[Int] = ???
def foo(m : Null)(implicit n: NonExistent): Unit = ???
sealed abstract class NonExistent

Note, however, that this won't protect you from variables containing null. There's no way to statically prevent that except using the @NonNull, which doesn't work well and has been deprecated.

The real answer is that any use of the word null is an error, unless you are calling Java. Let it throw a exception.

Upvotes: 3

0__
0__

Reputation: 67280

By default, and for Java interop, any reference type may be null. In the type system, Null is a subtype of anything deriving from AnyRef.

Conclusion: Simply don't use null values. There are very little reasons to do so in Scala.

Upvotes: 3

Related Questions