I encountered an unexpected behavior at runtime.
Consider the following code:
def execute[R](): R = (new Object).asInstanceOf[R] val r1: Unit = execute[Int]() // SUCCESS! val r2: Unit = execute[Nothing]() // class java.lang.Object cannot be cast to class scala.runtime.BoxedUnit val r3: Unit = execute[Unit]() // class java.lang.Object cannot be cast to class scala.runtime.BoxedUnit
It seems that when we have a
Unit, and we try to assign any other type to it, the value will be discarded (like with
Int). However, if we specify the type of the value as
Nothing, Scala will try to convert it to a
scala.runtime.BoxedUnit, which would result in an error in the case above.
My question is why does Scala try to convert
scala.runtime.BoxedUnit instead of discarding the value, like with any other type?
- macOS Mojave 10.14.5
- scala 2.13
- jdk 11.0.3