Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any differences between asInstanceOf[X] and toX for value types?

I used IntelliJ's ability to convert Java code to Scala code which generally works quite well.

It seems that IntelliJ replaced all casts with calls to asInstanceOf.

Is there any valid usage of asInstanceOf[Int], asInstanceOf[Long] etc. for value types which can't be replaced by toInt, toLong, ...?

like image 266
soc Avatar asked Dec 25 '10 01:12

soc


2 Answers

I do not know of any such cases. You can check yourself that the emitted bytecode is the same by compiling a class like

class Conv {
  def b(i: Int) = i.toByte
  def B(i: Int) = i.asInstanceOf[Byte]
  def s(i: Int) = i.toShort
  def S(i: Int) = i.asInstanceOf[Short]
  def f(i: Int) = i.toFloat 
  def F(i: Int) = i.asInstanceOf[Float]  
  def d(i: Int) = i.toDouble
  def D(i: Int) = i.asInstanceOf[Double]
}

and using javap -c Conv to get

public byte b(int);
  Code:
   0:   iload_1
   1:   i2b
   2:   ireturn

public byte B(int);
  Code:
   0:   iload_1
   1:   i2b
   2:   ireturn

...

where you can see that the exact same bytecode is emitted in each case.

like image 174
Rex Kerr Avatar answered Sep 21 '22 02:09

Rex Kerr


Well, toInt and toLong are not casts. The correct conversion of type casting is asInstanceOf indeed. For example:

scala> val x: Any = 5
x: Any = 5

scala> if (x.isInstanceOf[Int]) x.asInstanceOf[Int] + 1
res6: AnyVal = 6

scala> if (x.isInstanceOf[Int]) x.toInt + 1
<console>:8: error: value toInt is not a member of Any
       if (x.isInstanceOf[Int]) x.toInt + 1
                                  ^
like image 21
Daniel C. Sobral Avatar answered Sep 21 '22 02:09

Daniel C. Sobral