Skip to content

Commit

Permalink
SI-5866 Support casting null to value classes
Browse files Browse the repository at this point in the history
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 5589eee
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 2 deletions.
12 changes: 10 additions & 2 deletions src/compiler/scala/tools/nsc/transform/Erasure.scala
Expand Up @@ -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 {
Expand Down
2 changes: 2 additions & 0 deletions test/files/run/t5866.check
@@ -0,0 +1,2 @@
0.0
Foo(0.0)
11 changes: 11 additions & 0 deletions test/files/run/t5866.scala
@@ -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.