Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Boolean to String conversions

One way to convert true: Boolean onto a String is

scala> true.toString
res: String = true

However,

scala> true.asInstanceOf[String]
java.lang.ClassCastException: java.lang.Boolean cannot be cast to java.lang.String

Why the latter attempt fails ?

Many Thanks

like image 611
elm Avatar asked Jul 29 '14 18:07

elm


Video Answer


1 Answers

This is because Boolean isn't a subtype of String or type compatible with String

scala> val a: Any = "Hello"
a: Any = Hello

scala> val b = a.asInstanceOf[String]
b: String = Hello

scala> val c: Char = 123
c: Char = {

scala> val d = c.asInstanceOf[Int]
d: Int = 123

scala> (123).asInstanceOf[Double]
res0: Double = 123.0

scala> (1.3).asInstanceOf[Int]
res1: Int = 1

As you can see, I can easily cast any type compatible types back and forth, in this case numbers (including chars) are cross compatible. All types are compatible with Any, because Any just holds any arbitrary object reference, so as long as you "unbox" using the right types, you're golden.

scala> val arr = Array("Hello", 245, true)
arr: Array[Any] = Array(Hello, 245, true)

scala> val first = arr(0).asInstanceOf[String]
first: String = Hello

scala> val second = arr(1).asInstanceOf[Int]
second: Int = 245

scala> val third = arr(2).asInstanceOf[Boolean]
third: Boolean = true

This works fine, and as long as you're careful with how you unbox, you won't get any errors. This is how you'd do it in Java before generics were introduced to the language. That said, if you cast any one of the array elements to the wrong type, you'll get the cast exception.

The .toString method is different from a type cast, in that it's not a cast at all, it exists to serve as a concise way of converting any object, to a string representation of itself.

scala> val a = List(1,2,3,4)
a: List[Int] = List(1, 2, 3, 4)

scala> a.toString
res0: String = List(1, 2, 3, 4)

This is done so that any type can be printed if necessary, and has nothing to do with casting.

like image 179
Electric Coffee Avatar answered Oct 13 '22 16:10

Electric Coffee