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

The following Scala code is not compiled in Scala 2.7.7, with a "found: Zero (zero): T" mismatch error in 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 am fully aware of the viciousness of zeros, but suffice it to say that I really need to do this. Is this a compiler error or a programmer error?

Edit: Just to clarify, T is a type parameter, not a specific type. I did not understand that this was ambiguous in the original question until I read Karl's answer more carefully.

+6
scala compiler-errors
source share
4 answers

Apparently the correct way for this is in 2.7:

 class Key[T] class Entry[T](val k: Key[T], val v: T) def makeEntry[T >: Null] = new Entry(new Key[T], null) 
+7
source share

Here's a definition that spans null :

The Null type is a subtype of all reference types; its only instance is a null reference. Because Null is not a subtype of value types, null is not a member of any such type. For example, you cannot assign null to a variable of type Int.

In English, this means that you cannot assign null to a value type, but it is valid to assign to any reference type.

I am having trouble figuring out if T value or a reference type; but that will answer your question.

As you define T as a subtype of AnyRef , I assume it is ref, and the explanation of the error seems more likely; especially since Mitch Blevins just said that the code works under 2.8.

+4
source share

Try the following:

 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 "asInstanceOf [T]" is required, but it looks like.

+2
source share

Have you tried this?

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