Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you type cast Char/Int in Scala?

Tags:

casting

scala

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?

like image 805
CanisUrsa Avatar asked Nov 18 '10 15:11

CanisUrsa


People also ask

How do you declare a character in Scala?

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'.

Can you cast an int as a char in C?

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.


2 Answers

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 
like image 130
fedesilva Avatar answered Sep 26 '22 04:09

fedesilva


As everything is an Object in scala, you should use aNumber.toChar.

like image 41
Nicolas Avatar answered Sep 24 '22 04:09

Nicolas