我有一个关于 scala 类型安全的问题。事实上,在 Java 中我可以将泛型类型转换为对象。注释@SuppressWarning("unchecked")
完成了工作。然而在 scala 中我正在努力寻找一种方法来做到这一点。我已经尝试过Shapeless
API使用Typeable
课,也没用。这是我的代码片段:
class MyClass {
val data: HashMap[String, AnyRef] = new HashMap[String, AnyRef]();
def foo[T](key: String, value: Supplier[T]): T = synchronized {
data.computeIfAbsent(key, (s: String) => { value.get() }) //(1)
//(1) --> The compiler says : type mismatch; found : T required: AnyRef Note that T is unbounded, which means AnyRef is not a known parent.
// Such types can participate in value classes, but instances cannot appear in singleton types or in reference comparisons
}
}
这是data.computeIfAbsent()
签名:data.computeIfAbsent(x: String, y: Function[ _ >: String, _ <: AnyRef]): AnyRef
。我赋予data.computeIfAbsent()
的功能返回泛型类型 T
。我无法转换T
至AnyRef
,这就是为什么我收到上面的错误消息。
最佳答案
我建议通过使用HashMap[String, Any]
来避免这个特定问题,但要转换为AnyRef
,您只需编写value.get() .asInstanceOf[AnyRef]
。当然,
data.computeIfAbsent(key, (s: String) => { value.get().asInstanceOf[AnyRef] })
将返回AnyRef
,而不是T
。您可以使用
data.computeIfAbsent(key, (s: String) => { value.get().asInstanceOf[AnyRef] }).asInstanceOf[T]
它应该是安全的,但如果不安全,编译器不会帮助您发现错误。
关于java - 在 Scala 中将泛型类型转换为 AnyRef,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47252546/