【问题标题】:abstract type pattern is unchecked since it is eliminated by erasure抽象类型模式未选中,因为它已被擦除消除
【发布时间】:2013-08-08 21:18:04
【问题描述】:

谁能告诉我如何避免下面代码块中的警告:

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)
                   ^

【问题讨论】:

  • 第 1 行的T &lt;: Bar 是什么意思?
  • 这只是表示参数t的类型在T之上。或者换句话说,T是Bar或Bar本身的子类型。

标签: scala


【解决方案1】:

你可以使用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 _ => 
  }
}

【讨论】:

  • classtag 在这里做什么?
  • 假设你的意思是类参数签名中的ClassTag,它告诉编译器为类创建一个隐式ClassTag[T]参数,然后通过implicitly[ClassTag[T]]访问。 abstract class Foo[T: ClassTag]abstract class Foo[T](implicit tag: ClassTag[T]) 的糖
【解决方案2】:

另一种使用方式,特别是如果您希望使用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
    }
}

【讨论】:

  • 谢谢。我需要这个特性,并且无法完全进入隐式版本。干杯。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多