Wonpyo Park
Wonpyo Park

Reputation: 311

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?

Upvotes: 2

Views: 3778

Answers (2)

Dylan
Dylan

Reputation: 13859

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

Upvotes: 6

DevZer0
DevZer0

Reputation: 13525

As i mentioned if your use-case is to add additional functionality to an existing class such as string you can define an implict class

implicit class Foo(val s: String) {
    def inc = s.map(c => (c + 1).toChar)
}

and then if you can bring this class into scope you can perform the following action

"foobarstring".inc //strings now have a function called inc

more details on this topic http://docs.scala-lang.org/overviews/core/implicit-classes.html

Upvotes: 0

Related Questions