diff options
author | Martin Odersky <odersky@gmail.com> | 2012-07-30 14:30:17 +0200 |
---|---|---|
committer | Martin Odersky <odersky@gmail.com> | 2012-07-30 14:30:22 +0200 |
commit | 5589eeeb9a5e09352544efc629013caf2d18a842 (patch) | |
tree | 02529151d0f0b1ccefd5e7102bd392dbd5232d6d | |
parent | 1ad6e501997d332e2bc0ccc8dd40e3909e728930 (diff) | |
download | scala-5589eeeb9a5e09352544efc629013caf2d18a842.tar.gz scala-5589eeeb9a5e09352544efc629013caf2d18a842.tar.bz2 scala-5589eeeb9a5e09352544efc629013caf2d18a842.zip |
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.
-rw-r--r-- | src/compiler/scala/tools/nsc/transform/Erasure.scala | 12 | ||||
-rw-r--r-- | test/files/run/t5866.check | 2 | ||||
-rw-r--r-- | test/files/run/t5866.scala | 11 |
3 files changed, 23 insertions, 2 deletions
diff --git a/src/compiler/scala/tools/nsc/transform/Erasure.scala b/src/compiler/scala/tools/nsc/transform/Erasure.scala index 5115c49c87..24a74722b0 100644 --- a/src/compiler/scala/tools/nsc/transform/Erasure.scala +++ b/src/compiler/scala/tools/nsc/transform/Erasure.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 { diff --git a/test/files/run/t5866.check b/test/files/run/t5866.check new file mode 100644 index 0000000000..9f4ec729a7 --- /dev/null +++ b/test/files/run/t5866.check @@ -0,0 +1,2 @@ +0.0 +Foo(0.0) diff --git a/test/files/run/t5866.scala b/test/files/run/t5866.scala new file mode 100644 index 0000000000..120773effa --- /dev/null +++ b/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) + } +} |