如何在scala中将已擦除类型缩小(强制转换)为交叉类型?
考虑:如何在scala中将已擦除类型缩小(强制转换)为交叉类型?,scala,casting,pattern-matching,Scala,Casting,Pattern Matching,考虑: trait Base trait Derived extends Base class Narrow[T<:Base](arg :T) { val d = arg match { case derived :Derived => Some(derived) case _ => None } } 生成有关未检查(已删除)类型匹配的警告。因为编译器将在编译时删除带有泛型的模式匹配,并且所有匹配子句将匹配超类:派生的 对于这
trait Base
trait Derived extends Base
class Narrow[T<:Base](arg :T) {
val d = arg match {
case derived :Derived => Some(derived)
case _ => None
}
}
生成有关未检查(已删除)类型匹配的警告。因为编译器将在编译时删除带有泛型的模式匹配,并且所有匹配子句将匹配超类:
派生的
对于这种情况,可能是更好的解决方案:
class Narrow[T <: Base](arg: T)(implicit typeTag: TypeTag[T]) {
val d = arg match {
case derived if typeTag.tpe =:= typeOf[Derived] => println("I am ")
case derived if typeTag.tpe <:< typeOf[Derived] => println("Hello")
case _ => println("world")
}
}
class窄[T println(“我是”)
如果typeTag.tpe println(“Hello”),则派生大小写
案例=>println(“世界”)
}
}
仅匹配类型:Derived
首先,实际类型:Derived
匹配,无Derived
子类类型
匹配派生的
子类类型(即用T派生的
或T扩展派生的
,将其缩小),因为派生的
类型在第1条中已匹配,所以此子句现在将不匹配派生的
类型
与其他课程相匹配
case-derived:使用T@unchecked
进行派生。当然,使用@unchecked
意味着您必须确保代码是安全的,而不是编译器,但在这种情况下,我认为它与2.11.8之前一样安全(也就是说,由于类型擦除,客户端可以传递实际上不是T
的参数).1和2是错误的:它们的匹配取决于静态类型,而不是类。有点棘手的解决方案……但因为看起来我真正想要的是不可能的,可能是最好的。
class Narrow[T <: Base](arg: T)(implicit typeTag: TypeTag[T]) {
val d = arg match {
case derived if typeTag.tpe =:= typeOf[Derived] => println("I am ")
case derived if typeTag.tpe <:< typeOf[Derived] => println("Hello")
case _ => println("world")
}
}