Question

I just couldn't believe to my eyes when I saw the result... Just give a look to this code

object ScalaBug  {

  def main(args: Array[String]): Unit = {
    // This goes OK
    val aa: Option[Double] = first[Double]("A string in a Double!!") 
    println(aa)
    println(aa.getClass())
    aa match {
       // ...but this raises an error
       case Some(v) => println(v.getClass())
       case None => None
    }

    // The call to the other methods fails...
    val bb: Double = second[Double]("Yet another string in a Double!!") 
    println(bb)
    val cc: Option[Double] = third[Double]("One more string in a Double!!") 
    println(cc)

  }

  def first[T](x: String): Option[T] = Some(x.asInstanceOf[T])

  def second[T](x: String): T = x.asInstanceOf[T]

  def third[T](x: String): Option[T] = { val d = x.asInstanceOf[T] ; Some(d)}
}

It seems that the bug is in the call to the constructor method of Some(): no casting happens here...

In fact the third method does the same of the first method but in two different steps and I got an error as expected.

I think this should be considered a bug. But I'd like to share my point of view with you experts.

Just for sake of clarity, I'm on scala 2.10.2 but I got it also with scala 2.10.4-RC1

Was it helpful?

Solution

asInstanceOf in generic code simply promises the compiler that you know that one thing is actually something else. Whenever you get out of generic code and rely upon this behavior, false promises will blow up in your face.

This is how the JVM works: you need a specific class to test instanceof.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top