Ok, I know better than to use nulls as a design choice, but in this case I have to. Why the following does not compile?
def test[T<:AnyRef](o :Option[T]) :T = o getOrElse null
Error:(19, 53) type mismatch;
found : Null(null)
required: T
Note: implicit method foreignKeyType is not applicable here because it comes after the application point and it lacks an explicit result type
def test[T<:AnyRef](o :Option[T]) :T = o getOrElse null
^
Null is a subtype of all reference types, but the fact that T is a subtype of AnyRef doesn't guarantee that T is a reference type -- in particular, Nothing is a subtype of AnyRef which does not contain null.
Your code Works if you add a lower bound:
It works:
I don't know why this does not work -
Null
is a subtype of all reference types in Scala, so you would expect that this would work with anyT <: AnyRef
. You can make it work withasInstanceOf
:(Try to avoid using
null
whenever possible in Scala - I can imagine you'd have a legitimate use case, for example when you need to pass data to Java code).By the way,
Option
has a methodorNull
which will return the value of an option if it is aSome
andnull
if it isNone
.