Last active
February 25, 2016 04:08
-
-
Save mather/9eb722b47a00e1afe863 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ClassTagを付けない場合は型消去によりTの情報が失われ、すべて1つ目でマッチしてしまう。また、そのことに関するコンパイル時警告が出る。