我对这里发生的事情感到困惑:

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 警告。这里发生了什么?

最佳答案

在 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) =>
    }
  }
}

Newer answers of this question have more details.

关于scala - Scala 中的类型删除,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38570948/

10-11 22:55
查看更多