Reputation: 448
The following are valid statements in Scala:
scala> var x: Option[Int] = Some(3)
x: Option[Int] = Some(3)
scala> var x: Option[Int] = None
x: Option[Int] = None
The following is invalid:
scala> var x: Option[Int] = 3
<console>:7: error: type mismatch;
found : Int(3)
required: Option[Int]
var x: Option[Int] = 3
So far these examples make sense to me; a value of type Option[T] can be either of type Some[T] or None, so the compiler prevents you from assigning a value which is of neither type.
However, the Scala compiler appears to accept this:
scala> val x: Option[Int] = null
x: Option[Int] = null
If I then try to do a pattern match on the option (e.g. as below), I'll get failures I didn't expect - why doesn't the compiler protect me from this by rejecting the assignment of null?
x match {
case Some(y) => println("Number: ", y)
case None => println("No number")
}
Upvotes: 0
Views: 1499
Reputation: 1143
The answer to the question you probably intended to ask goes something like this:
Idiomatic Scala will never use null
. Null references exist purely for interoperability with Java and other JVM languages. If you see null
in Scala code it should immediately attract scrutiny. You would never use null
by mistake so a compiler warning is unnecessary. As noted in Daniel Sobral's answer and the comments the compiler cannot provide protection against null
.
Upvotes: 0
Reputation: 297195
If you look at the Scala class hierarchy, you'll see that all classes deriving from AnyRef
are super classes of Null
, and any such super class can be assigned the value null
. Since Option
is one such class, you can assign Null
to it.
Note that both Some
and None.type
(that is, the singleton type of the None
object) are super classes of Null
, so null
is a valid value for either one.
You cannot assign 3
to Option
because 3
is not a value of a sub class of Option
(evidently).
Upvotes: 7