【发布时间】:2016-01-11 07:45:12
【问题描述】:
在下面的代码中,我希望仅当 i 的类型为 A 时才调用 hitA。要检查的类型作为类型参数提供,因此它被类型擦除并且match 失败,给我一个编译器警告:
抽象类型模式 T 未被选中,因为它被擦除消除了
代码的期望输出是:
点击A
未命中
在当前版本中,当我运行代码时,我得到 Hit A,后跟 ClassCastException。
我了解正在发生的事情以及为什么会出现警告和异常,但我不知道如何解决这个问题。我已阅读有关 TypeTags 的基本文章,并且了解如何在基本情况下使用它们,但我看不到如何使用 TypeTags 创建部分函数。
import scala.reflect.runtime.universe._
object TestMatch extends App {
abstract class I
class A extends I {
def hitA() = println("Hit A")
}
class B extends I
def processOpGen[T <: I : TypeTag](op: PartialFunction[I, Unit])(i: I) = {
val fallback : PartialFunction[I, Unit] = {case _ => println("Not hit")}
(op orElse fallback)(i)
}
def partialMatchGen[T <: I : TypeTag](op: T => Unit)(i: I) = {
processOpGen[T] {
case c: T => op(c) // can TypeTag be used here for matching somehow?
}(i)
}
partialMatchGen[A](a => a.hitA())(new A)
partialMatchGen[A](a => a.hitA())(new B)
}
【问题讨论】:
-
这篇文章可能会有所帮助 - stackoverflow.com/questions/12218641/…。我正在用它来尝试回答这个问题。你想在这条线上匹配什么:
case c: T => op(c)? -
当
c是T(或其子类)时,我想对c执行一些操作。可以使用I中的接口和A中的实现,但我想这样做而不修改I和A类。
标签: scala pattern-matching type-erasure