scala - Why can I assign null to an Option? -


the following 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 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 me; value of type option[t] can either of type some[t] or none, compiler prevents assigning value of neither type.

however, scala compiler appears accept this:

scala> val x: option[int] = null x: option[int] = null 

if try pattern match on option (e.g. below), i'll failures didn't expect - why doesn't compiler protect me rejecting assignment of null?

x match {   case some(y) => println("number: ", y)   case none => println("no number") } 

if @ scala class hierarchy, you'll see classes deriving anyref super classes of null, , such super class can assigned value null. since option 1 such class, can assign null it.

note both some , none.type (that is, singleton type of none object) super classes of null, null valid value either one.

you cannot assign 3 option because 3 not value of sub class of option (evidently).


Comments

Popular posts from this blog

java - Run a .jar on Heroku -

java - Jtable duplicate Rows -

validation - How to pass paramaters like unix into windows batch file -