【问题标题】:Scala - type erasure? [duplicate]Scala - 类型擦除? [复制]
【发布时间】:2012-08-12 17:29:19
【问题描述】:

可能重复:
How do I get around type erasure on Scala? Or, why can't I get the type parameter of my collections?

我运行了以下代码:

scala>  var s = new Stack()push(1)
s: scalatest.Stack[Int] = 1 

scala>  s match { case s : Stack[String] => print("Hello")}
<console>:12: warning: non variable type-argument String in type pattern scalatest.Stack[String] is unchecked since it is eliminated by erasure
              s match { case s : Stack[String] => print("Hello")
}

Stack 是取自 http://www.scala-lang.org/node/129 的类。如果我在没有-unchecked 标志的情况下运行此代码,它将打印“Hello”。为什么会这样?

【问题讨论】:

  • 编译器告诉你有问题,是什么问题。你为什么在这里问这个?

标签: scala types type-erasure


【解决方案1】:

问题是您将s 匹配为Stack[String] 类型。在运行时,可以确定s 是否属于Stack 类型,但由于Java 的type erasure 无法确定s 是否属于Stack[String]、Stack[Int] 等类型。所以无论如何类型参数是,它与case 表达式匹配。这就是 Scala 发出警告的原因。就像你匹配为一样

s match { case s : Stack[_] => print("Hello")}

(编译时不会出现警告)。


编辑: 一种解决方法(也适用于 Java)是创建一个不再具有类型参数的特定类。例如:

import scala.collection.mutable.Stack;

object Test extends App {
  class MyStack extends Stack[Int];
  class MyOtherStack extends Stack[String];

  val s: Stack[_] = new MyStack().push(1);

  s match {
    case s : MyOtherStack => print("Hello String");
    case s : MyStack => print("Hello Int");
  }
}

它有一个缺点,您不能将它用于不可变容器,因为它们的方法会创建新对象,并且它们不会是这些特定子类的实例。

【讨论】:

  • 啊,好吧...所以泛型在 Scala 中没有具体化
猜你喜欢
  • 2020-07-27
  • 2012-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-30
  • 1970-01-01
相关资源
最近更新 更多