Java.lang.Integer cannot be passed to java.lang.Byte error with any type in Scala

I can pass Int data to Byte.

scala> 10.asInstanceOf[Byte]
res8: Byte = 10

      

However, with the same value in either type, casting 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)

      

I can do it twice.

scala> val y = x.asInstanceOf[Int]
y: Int = 10

scala> y.asInstanceOf[Byte]
res11: Byte = 10

      

Are there any better ways than this?

+3


source to share


3 answers


In Scala, the compiler tries to hide the distinction between primitive types and reference (boxed) types, the default for primitives. Sometimes abstraction leaks and you see problems like this.

Here you are pretending to be an Any value, which requires the compiler to revert back to the boxed values:

override def set(value:Any) = {
    if (check(value.asInstanceOf[Byte])) {

      

And here you do not restrict the value by reference, so such casting will be done on primitive types:

10.asInstanceOf[Byte]

      



In other words:

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 additional conversion, say to String:

scala> x.toString.toInt
res6: Int = 10

scala> x.toString.toByte
res7: Byte = 10

      

+7


source


Try converting to int and then to Byte:

scala> val x : Any = 10
x: Any = 10

scala> x.asInstanceOf[Int].asInstanceOf[Byte]
res1: Byte = 10

      

Or as Ionuts G. Stan suggested:



scala> x.asInstanceOf[Int].toByte
res4: Byte = 10

      

Although I cannot explain why this works.

+3


source


An integer is 32 bits in Java and a byte is 8 bits. The problem is, what bits do you truncate to make the integer a byte? Least significant 24 bits or most significant 24 bits? The correct answer is in the context of your problem.

0


source







All Articles