Wonpyo Park Wonpyo Park - 11 months ago 70
Scala Question

Scala Cast object to another type

I want to make following code not throw any error

case class A(value: String)
val a = A("I hope to be string one day")
val value = a.asInstanceOf[String] // java.lang.ClassCastException: A cannot be cast to java.lang.String

I want to modify class A such that below work

val value = a.asInstanceOf[String] // I hope to be string one day

does anybody knows the solution?

Answer Source

A cannot be cast to a String because it is not a String. There is nothing you can do to make a.asInstanceOf[String] work.

That said, you could convert from A to String, either explicitly or implicitly:

// explicit
val s: String = a.value

// implicit conversion (although typically frowned-upon as bad practice)
implicit def unwrapA(a: A): String = a.value
val s: String = a