Created
August 13, 2014 07:31
-
-
Save mather/6e51cc681807f2ed52fa to your computer and use it in GitHub Desktop.
Scalaで型消去を回避する ref: http://qiita.com/mather314/items/67fdbf8293edc0200444
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
| class A | |
| class B extends A | |
| class C extends A | |
| def isType[T <: A](a: A) = a.isInstanceOf[T] | |
| // <console>:9: warning: abstract type T is unchecked since it is eliminated by erasure | |
| // def isType[T <: A](a: A) = a.isInstanceOf[T] | |
| // ^ | |
| // isType: [T <: A](a: A)Boolean |
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
| scala> isType[A](new A) | |
| res11: Boolean = true | |
| scala> isType[C](new B) | |
| res12: Boolean = true // 本当は (new B).isInstanceOf[C] => false |
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
| def isType[T <: A](a: A)(implicit e: scala.reflect.ClassTag[T]) = e.runtimeClass.isInstance(a) | |
| //=> isType: [T <: A](a: A)(implicit e: scala.reflect.ClassTag[T])Boolean |
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
| scala> isType[C](new B) | |
| res13: Boolean = false |
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 | |
| def isType[T <: A : ClassTag](a: A) = implicitly[ClassTag[T]].runtimeClass.isInstance(a) |
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 | |
| def isType[T <: A : ClassTag](a: A) = a match { | |
| case t: T => true | |
| case _ => false | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment