I am having issues getting this cast to work.
The compiler tells me value aNumber
is not a member of object Char
def runCastTest() { val aNumber = 97 val aChar = (Char)aNumber println(aChar) // Should be 'a' }
What am I doing wrong?
Scala Char |(x: Char) method with exampleThe |(x: Char) method is utilized to find the bit-wise OR of the stated character value and given 'x' in the argument list. Return Type: It returns the bit-wise OR of the stated character value and given 'x'.
We can convert an integer to the character by adding a '0' (zero) character. The char data type is represented as ascii values in c programming. Ascii values are integer values if we add the '0' then we get the ASCII of that integer digit that can be assigned to a char variable.
You are not casting. With (Char)aNumber
you are trying to invoke a method aNumber
in the object Char:
scala> val aNumber = 97 aNumber: Int = 97 scala> val aChar = (Char)aNumber <console>:5: error: value aNumber is not a member of object Char val aChar = (Char)aNumber ^
You can do
scala> aNumber.asInstanceOf[Char] res0: Char = a
or as Nicolas suggested call toChar
on the Int instance:
scala> aNumber.toChar res1: Char = a
As everything is an Object in scala, you should use aNumber.toChar
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With