soc*_*soc 13 java language-features casting scala
我使用IntelliJ的能力将Java代码转换为Scala代码,这些代码通常运行良好.
似乎IntelliJ通过调用取代了所有演员阵容asInstanceOf
.
是否有任何有效的使用asInstanceOf[Int]
,asInstanceOf[Long]
等等.对于不能被替换值类型toInt
,toLong
...?
Rex*_*err 16
我不知道有这种情况.您可以通过编译类来检查自己发出的字节码是否相同
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]
}
Run Code Online (Sandbox Code Playgroud)
并javap -c Conv
用来获得
public byte b(int);
Code:
0: iload_1
1: i2b
2: ireturn
public byte B(int);
Code:
0: iload_1
1: i2b
2: ireturn
...
Run Code Online (Sandbox Code Playgroud)
在那里你可以看到在每种情况下发出完全相同的字节码.
好了,toInt
并且toLong
都没有施放.asInstanceOf
确实是类型铸造的正确转换.例如:
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
^
Run Code Online (Sandbox Code Playgroud)