问题描述
我可以将 Int 数据转换为 Byte.
I can cast Int data to Byte.
scala> 10.asInstanceOf[Byte]
res8: Byte = 10
但是在 Any 类型中使用相同的值时,强制转换会引发错误.
However with the same value in Any type, the cast raises an error.
scala> val x : Any = 10
x: Any = 10
scala> x.asInstanceOf[Byte]
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Byte
at scala.runtime.BoxesRunTime.unboxToByte(BoxesRunTime.java:98)
at .<init>(<console>:10)
我可以施放两次.
scala> val y = x.asInstanceOf[Int]
y: Int = 10
scala> y.asInstanceOf[Byte]
res11: Byte = 10
还有比这更好的方法吗?
Are there better ways than this?
推荐答案
在 Scala 中,编译器试图隐藏原始类型和引用类型(盒装)之间的区别,默认为原始类型.有时,抽象泄漏,您会看到类似的问题.
In Scala, compiler tries to hide the distinction between primitive types and reference ones (boxed), defaulting to primitives. Sometimes, abstractions leak and you see that kind of problems.
在这里,您假装值是 Any,这需要编译器回退到装箱值:
Here, you're pretending that value is Any, which require compiler to fallback to boxed values:
override def set(value:Any) = {
if (check(value.asInstanceOf[Byte])) {
在这里,您没有将值限制为引用,因此此类转换将在原始类型上完成:
And here, you're not limiting value to be referential, so such casting will be done on primitive types:
10.asInstanceOf[Byte]
换句话说:
scala> val x: Any = 10
x: Any = 10
scala> x.asInstanceOf[Byte]
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Byte
at scala.runtime.BoxesRunTime.unboxToByte(BoxesRunTime.java:97)
... 32 elided
scala> val y: Int = 10
y: Int = 10
scala> y.asInstanceOf[Byte]
res4: Byte = 10
要克服这个问题,您可能需要进行额外的转换,例如字符串:
To overcome this problem, you probably have to go through an extra conversion to, say, String:
scala> x.toString.toInt
res6: Int = 10
scala> x.toString.toByte
res7: Byte = 10
这篇关于java.lang.Integer 不能转换为 java.lang.Byte 错误与 Scala 中的任何类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!