CanisUrsa
CanisUrsa

Reputation: 465

How do you type cast Char/Int in 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?

Upvotes: 28

Views: 29596

Answers (2)

fedesilva
fedesilva

Reputation: 1532

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

Upvotes: 43

Nicolas
Nicolas

Reputation: 24759

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

Upvotes: 19

Related Questions