我对这里发生了什么感到很困惑:
import scala.collection.immutable._
object Main extends App {
sealed trait Node
sealed trait Group
case class Sheet(
val splat: String,
val charname: String,
val children: ListMap[String, Node],
val params0: ListMap[String, Param], //params0 to separate sheet-general parameters
val note: Option[Note]
) extends Node with Group
case class Attributes(val name: String) extends Node with Group
case class Param(val name: String, val value: String) extends Node
case class Note(val note: String) extends Node我有三个版本的替换函数--最后一个是我正在尝试编写的版本,其他版本只是调试。
class SheetUpdater(s: Sheet) {
def replace1[T <: Group](g: T): Unit = {
s.children.head match {
case (_, _:Sheet) =>
case (_, _:Attributes) =>
}
}
}此版本不引发警告,因此显然我可以在运行时访问该类型的s.children。
class SheetUpdater(s: Sheet) {
def replace2[T <: Group](g: T): Unit = {
g match {
case _:Sheet =>
case _:Attributes =>
}
}
}这个版本也没有,所以显然g类型的细节在运行时也是可用的.
class SheetUpdater(s: Sheet) {
def replace3[T <: Group](g: T): Unit = {
s.children.head match {
case (_, _:T) => //!
case (_, _:Attributes) =>
}
}
}..。但即便如此,这最终还是给了我可怕的Abstract type pattern T is unchecked since it is eliminated by erasure警告。这里发生了什么事?
发布于 2016-07-25 15:49:14
在Scala中,泛型在运行时被删除,这意味着List[Int]和List[Boolean]的运行时类型实际上是相同的。这是因为JVM作为一个整体擦除泛型类型。所有这些都是因为JVM希望在泛型首次引入时保持向后兼容的方式.
在Scala中有一种使用ClassTag的方法,它是一个隐式参数,然后可以使用您使用的任何泛型来线程化。
您可以将: ClassTag看作是将泛型类型作为参数传递。(它是传递ClassTag[T]类型隐式参数的语法糖。)
import scala.reflect.ClassTag
class SheetUpdater(s: Sheet) {
def replace3[T <: Group : ClassTag](g: T): Unit = {
s.children.head match {
case (_, _:T) => //!
case (_, _:Attributes) =>
}
}
}https://stackoverflow.com/questions/38570948
复制相似问题