27

Could someone tell me how can I avoid the warning in the code block below:

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

This results in a compiler warning:

 abstract type pattern T is unchecked since it is eliminated by erasure
 case CaseClass(t: T) => println(t)
                   ^
Harshal Pandya
  • 1,622
  • 1
  • 15
  • 17

2 Answers2

30

You could use ClassTag (or 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 _ => 
  }
}
thSoft
  • 21,755
  • 5
  • 88
  • 103
senia
  • 37,745
  • 4
  • 88
  • 129
  • 2
    What does classtag do here? – Blankman Jan 28 '17 at 00:01
  • 1
    Assuming you mean `ClassTag` in the class parameter signature, it tells the compiler to create an implicit `ClassTag[T]` parameter for the class, which is then accessed via `implicitly[ClassTag[T]]`. `abstract class Foo[T: ClassTag]` is sugar for `abstract class Foo[T](implicit tag: ClassTag[T])` – WeaponsGrade Jul 18 '18 at 19:29
3

Another variation to use, especially if you desire to use a trait (as opposed to using a class or abstract class which the other solution requires), looks like this:

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
    }
}
chaotic3quilibrium
  • 5,661
  • 8
  • 53
  • 86