Reputation: 64207
As far as I know, in Java I can
Object o = new String("abc")
String s = (String) o
But how to rewrite it in Scala?
val o: java.lang.Object = new java.lang.String("abc")
val s: String = // ??
A Java library I want to use returns java.lang.Object
which I need to cast to a more specific type (also defined in this library). A Java example does it exactly the way like the first example of mine, but just using Scala's source: TargetType
instead of Java's (TargetType)source
doesn't work.
Upvotes: 20
Views: 22569
Reputation: 1384
For the sake of future people having this issue, Travi's previous answer is correct and can be used for instance in Yamlbeans to map Desearialized objects to Maps doing something like:
val s: java.util.Map[String,String] = obj.asInstanceOf[java.util.Map[String,String]]
I hope this little comment comes handy for one in the future as a detail over the answer I found here.
Upvotes: 5
Reputation: 297185
Here's a safe way of doing it:
val o: java.lang.Object = new java.lang.String("abc")
o match { case s: String => /* do stuff with s */ }
If you need to return the result, this works as well:
import PartialFunction._
def onlyString(v: Any): Option[String] = condOpt(v) { case x: String => x }
val s: Option[String] /* it might not be a String! */ = onlyString(o)
Upvotes: 11
Reputation: 139038
If you absolutely have to—for compatibility with a Java library, for example—you can use the following:
val s: String = o.asInstanceOf[String]
In general, though, asInstanceOf
is a code smell and should be avoided.
Upvotes: 26