Null as a type parameter instance
Okay, I know better than using zeros as a design, but in this case I have to do it. Why doesn't the following 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
^
source to share
Null is a subtype of all reference types, but the fact that T is a subtype of AnyRef does not guarantee that T is a reference type - in particular, Nothing is a subtype of AnyRef that does not contain null.
Your code Works if you add a bottom border:
def test[T >:Null <:AnyRef](o :Option[T]) :T = o getOrElse null;
Works:
scala> def test[T >:Null <:AnyRef](o :Option[T]) :T = o getOrElse null;
test: [T >: Null <: AnyRef](o: Option[T])T
scala>
scala>
scala> test(None)
res0: Null = null
scala> test(Some(Some))
res1: Some.type = Some
source to share
I don't know why it doesn't work. Null
is a subtype of all reference types in Scala, so you would expect this to work with anyone T <: AnyRef
. You can make it work with asInstanceOf
:
def test[T <: AnyRef](o: Option[T]): T = o getOrElse null.asInstanceOf[T]
(Try to avoid using Null
it whenever possible in Scala - I can imagine you would have a legitimate use case, such as when you need to pass data into Java code).
By the way, it Option
has a method orNull
that will return the parameter value, if it is Some
and Null
if it is None
.
source to share