Scala cast to generic type

boxing, casting, scala, type-erasure

Solution

`a.asInstanceOf[B]` means:

Dear compiler;

Please forget what you think the type of `a` is. I know better. I know that if `a` isn't actually type `B` then my program could blow up, but I'm really very smart and that's not going to happen.

Sincerely yours, Super Programmer

In other words `val b:B = a.asInstanceOf[B]` won't create a new variable of type `B`, it will create a new variable that will be treated as if it were type `B`. If the actual underlying type of `a` is compatible with type `B` then everything is fine. If `a`'s real type is incompatible with `B` then things blow up.

Problem

I'm confused about the generic type. I expect that `2.asInstanceOf[A]` is cast to the type `A`, meanwhile, it's cast to `Int`. Besides that, the input is `java.lang.Long` whereas the output is a list of `Int` (according to the definition the input and the output should be the same type). Why is that? ``` def whatever[A](x: A): List[A] = { val two = 2.asInstanceOf[A] val l = List(1.asInstanceOf[A],2.asInstanceOf[A]) println(f"Input type inside the function for 15L: ${x.getClass}") println(f"The class of two: ${two.getClass}, the value of two: $two") println(f"The class of the first element of l: ${l.head.getClass}, first element value: ${l.head}") l } println(f"Returned from whatever function: ${whatever(15L)}") ``` the outupt: ``` Input type inside the function for 15L: class java.lang.Long The class of two: class java.lang.Integer, the value of two: 2 The class of the first element of l: class java.lang.Integer, first element value: 1 Returned from whatever function: List(1, 2) ```

Original source

Related problems