Search code examples
scalascala-2.11

How can I prevent an Scala function to receive 'null' as an argument


I've got a Scala method with this signature:

  def m (map: Map [String, _])

I suppose Map is a reference type and as such, I can call m passing null

  m (null) // Allowed call

Is there any way for the compiler to do not allow null is some method calls? Other languages like Kotlin allow this by explicitly saying that a parameter can be null: http://kotlinlang.org/docs/reference/null-safety.html

Is there anything like that in Scala?

EDIT: Thank you for your comments. I understand that 'null' references are a runtime matter, but other languages with other type systems take care of this at compile time.

I only wanted to know if there was a way in Scala too (I'm starting to use the language). Checking the comments, the answer, and the Scala type hierachy I guest this is not possible.

For value objects (like immutable collections and case classes) it could make sense to avoid 'null' (however they extend AnyRef).

I could try to avoid 'null', but for example Map.get returns 'null' if the key is not found, so I have to handle this.

Regarding the Map[String, _] it is a heterogenous map, think of it as a JSON object. May I handle this in a different, more Scala-like way?

Thanks!


Solution

  • Any reference type (AnyRef) can, by definition of the JVM, be null, and the compiler cannot enforce that no client side calls your function with null.

    I highly recommend not using null values at all when working with Scala. If you need to handle absent values, use the Option type instead.