首页 文章

抽象类型模式是未选中的,因为它是通过擦除来消除的

提问于
浏览
23

有人可以告诉我如何避免下面的代码块中的警告:

abstract class Foo[T <: Bar]{
  case class CaseClass[T <: Bar](t: T)
  def method1 = {
    case CaseClass(t: T) => println(t)
    csse _ => 
  }
}

这会导致编译器警告:

abstract type pattern T is unchecked since it is eliminated by erasure
 case CaseClass(t: T) => println(t)
                   ^

2 回答

  • 2

    你可以使用 ClassTag (或 TypeTag ):

    import scala.reflect.ClassTag
    
    abstract class Foo[T <: Bar : ClassTag]{
      ...
      val clazz = implicitly[ClassTag[T]].runtimeClass
      def method1 = {
        case CaseClass(t) if clazz.isInstance(t) => println(t) // you could use `t.asInstanceOf[T]`
        case _ => 
      }
    }
    
  • 24

    另一种使用的变体,特别是如果你想使用 trait (而不是使用其他解决方案需要的 classabstract class ),看起来像这样:

    import scala.reflect.{ClassTag, classTag}
    
    trait Foo[B <: Bar] {
      implicit val classTagB: ClassTag[B] = classTag[B]
      ...
      def operate(barDescendant: B) =
        barDescendant match {
          case b: Bar if classTagB.runtimeClass.isInstance(b) =>
            ... //do something with value b which will be of type B
        }
    }
    

相关问题