java - 在 Scala 中将泛型类型转换为 AnyRef

标签 java scala

我有一个关于 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 。我无法转换TAnyRef ,这就是为什么我收到上面的错误消息。

最佳答案

我建议通过使用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/

相关文章:

java - 我如何知道对象实例使用什么类型的变量?

java - 开始一个新的 Activity (安卓)

java - 在项目点击时发送字符串

scala - 在 akka 消息中保留类型/类标签

scala - 如何在 Apache Spark scala 中读取 PDF 文件和 xml 文件?

scala - Akka-Http:如何返回参与者的响应?

java - 循环中未使用的变量

java - 通过 AngularJS 上传文件后从 Spring Controller 返回 Json

Scala - toList 与 ListBuffer 上的结果?

scala - 如何在 Scala 中进行泛型元组 -> 案例类转换?