如何将 java.lang.Object 转换为 Scala 中的特定类型?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9816129/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to cast java.lang.Object to a specific type in Scala?
提问by Ivan
As far as I know, in Java I can
据我所知,在Java中我可以
Object o = new String("abc")
String s = (String) o
But how to rewrite it in Scala?
但是如何在 Scala 中重写它呢?
val o: java.lang.Object = new java.lang.String("abc")
val s: String = // ??
A Java library I want to use returns java.lang.Objectwhich 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: TargetTypeinstead of Java's (TargetType)sourcedoesn't work.
我想使用返回的 Java 库java.lang.Object,我需要将其转换为更具体的类型(也在这个库中定义)。Java 示例与我的第一个示例完全一样,但仅使用 Scalasource: TargetType而非 Java 是(TargetType)source行不通的。
回答by Travis Brown
If you absolutely have to—for compatibility with a Java library, for example—you can use the following:
如果您绝对必须——例如,为了与 Java 库兼容——您可以使用以下内容:
val s: String = o.asInstanceOf[String]
In general, though, asInstanceOfis a code smell and should be avoided.
但总的来说,这asInstanceOf是一种代码异味,应该避免。
回答by Daniel C. Sobral
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)
回答by David Pelaez
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:
为了将来遇到这个问题的人,Travi 之前的答案是正确的,例如可以在 Yamlbeans 中使用,将 Desearialized 对象映射到 Maps,执行如下操作:
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.
我希望这个小小的评论在未来作为我在这里找到的答案的详细信息对一个人有用。

