Skip to content

Instantly share code, notes, and snippets.

@mather
Last active February 25, 2016 04:08
Show Gist options
  • Select an option

  • Save mather/9eb722b47a00e1afe863 to your computer and use it in GitHub Desktop.

Select an option

Save mather/9eb722b47a00e1afe863 to your computer and use it in GitHub Desktop.
import scala.reflect.ClassTag
object Hoge {
def main(args: Array[String]) = {
val s = new Hoge[StringSample]
val i = new Hoge[IntSample]
s.detectType(StringSample("hogehoge")) //=> detected!
s.detectType(IntSample(1))
i.detectType(StringSample("hogehoge"))
i.detectType(IntSample(2)) //=> detected!
}
}
class Hoge[T <: Sample : ClassTag] {
def detectType(obj: Any) = obj match {
case t: T => println("detected!")
case _ => println("unknown type.")
}
}
abstract class Sample
case class StringSample(str: String) extends Sample
case class IntSample(i: Int) extends Sample
@mather
Copy link
Author

mather commented Aug 12, 2014

ClassTagを付けない場合は型消去により T の情報が失われ、すべて1つ目でマッチしてしまう。
また、そのことに関するコンパイル時警告が出る。

Hoge.scala:16: warning: abstract type pattern T is unchecked since it is eliminated by erasure
    case t: T => println("detected!")
            ^
one warning found

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment