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开发者_JAVA技巧[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.
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)
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 .
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.
Have you tried this?
def makeEntry[T <: AnyRef] = new Entry[T](new Key[T], null: T)
精彩评论