20

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.

3 Answers 3

26

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Seems working. And yes, I absolutely need this - for compatibility with a Java library. Thanks.
11

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)

1 Comment

In some cases I feel like this is probably overkill, and asInstanceOf is just fine—e.g. deserializing with readObject, when you're stuck with libraries that use pre-generics Java collections, etc. I was assuming this was one of those cases.
5

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.