Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala 2.7.x type mismatch error when passing null for a reference type

The following Scala code fails to compile in Scala 2.7.7, with a type mismatch error "found: Null(null) required: T" on the last line:

/**
 * @param [T] key type
 */
class Key[T] 

class Entry[T](val k: Key[T], val v: T)

def makeEntry[T <: AnyRef] = new Entry[T](new Key[T], null)

I'm fully aware of the evilness of nulls, but suffice it to say that I actually need to do this. Is this a compiler bug or programmer error?

Edit: Just to clarify, T is a type parameter and not a concrete type. I didn't realize this was ambiguous in the original question until I read Carl's response more carefully.

like image 466
Aaron Novstrup Avatar asked Dec 10 '09 21:12

Aaron Novstrup


3 Answers

Apparently the correct way to do this in 2.7 is:

class Key[T]

class Entry[T](val k: Key[T], val v: T)

def makeEntry[T >: Null] = new Entry(new Key[T], null)
like image 53
Aaron Novstrup Avatar answered Sep 18 '22 18:09

Aaron Novstrup


Here's the definition that covers null:

Type Null is a subtype of all reference types; its only instance is the null reference. Since Null is not a subtype of value types, null is not a member of any such type. For instance, it is not possible to assign null to a variable of type Int.

In English, this is saying you can't assign null to a value type but it's valid to assign to any reference type.

I'm having some trouble figuring out whether T is a value or reference type; but that would answer your question.

As you define T to be a subtype of AnyRef, I guess it's a ref and the "bug" explanation seems the more likely; especially as Mitch Blevins just said the code works under 2.8 .

like image 37
Carl Smotricz Avatar answered Sep 18 '22 18:09

Carl Smotricz


Try this:

class Key[T <: AnyRef]

class Entry[T <: AnyRef](val k: Key[T], val v: T)

def makeEntry[T <: AnyRef] = new Entry[T](new Key[T], null.asInstanceOf[T])

I'm not sure why the "asInstanceOf[T]" is required, but it seems to be.

like image 24
Erik Engbrecht Avatar answered Sep 18 '22 18:09

Erik Engbrecht