Permalink
Browse files

SI-5866 Support casting null to value classes

The fix now supports null.asInstanceOf[C] where C is a value class that wraps a primitive type.
  • Loading branch information...
odersky committed Jul 30, 2012
1 parent 1ad6e50 commit 5589eeeb9a5e09352544efc629013caf2d18a842
Showing with 23 additions and 2 deletions.
  1. +10 −2 src/compiler/scala/tools/nsc/transform/Erasure.scala
  2. +2 −0 test/files/run/t5866.check
  3. +11 −0 test/files/run/t5866.scala
@@ -563,8 +563,16 @@ abstract class Erasure extends AddInterfaces
case _ =>
val clazz = tref.sym
log("not boxed: "+tree)
val tree0 = adaptToType(tree, clazz.tpe)
cast(Apply(Select(tree0, clazz.derivedValueClassUnbox), List()), pt)
lazy val underlying = underlyingOfValueClass(clazz)
val tree0 =
if (tree.tpe.typeSymbol == NullClass &&
isPrimitiveValueClass(underlying.typeSymbol)) {
// convert `null` directly to underlying type, as going
// via the unboxed type would yield a NPE (see SI-5866)
unbox1(tree, underlying)
} else
Apply(Select(adaptToType(tree, clazz.tpe), clazz.derivedValueClassUnbox), List())
cast(tree0, pt)
}
case _ =>
pt.typeSymbol match {
@@ -0,0 +1,2 @@
0.0
Foo(0.0)
@@ -0,0 +1,11 @@
class Foo(val d: Double) extends AnyVal {
override def toString = s"Foo($d)"
}
object Test {
def main(args: Array[String]): Unit = {
val d: Double = null.asInstanceOf[Double]
println(d)
val f: Foo = null.asInstanceOf[Foo]
println(f)
}
}

0 comments on commit 5589eee

Please sign in to comment.