Search code examples
scalagenericsnulltype-parameter

null as instance of a type parameter


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
                                                   ^

Solution

  • 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:

    def test[T >:Null <:AnyRef](o :Option[T]) :T = o getOrElse null;
    

    It 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