I\'ve tried two ways to constrain a generic type parameter to a nullable type, but both seem to have some unexpected problems.
First attempt (using T <: AnyRef):
def testAnyRefConstraint[T >: Null <: AnyRef](option:Option[T]):T = {
option getOrElse null
}
I felt really stupid when I made this error the first time. Just because something extends AnyRef
doesn't mean it must be nullable. For instance, Nothing
is a subtype of AnyRef
, and it is not nullable.
The other way around is similar, because Any
is a supertype of Null
, and any Int
is also an Any
.