Skip to content

Instantly share code, notes, and snippets.

@mather
Created August 13, 2014 07:31
Show Gist options
  • Select an option

  • Save mather/6e51cc681807f2ed52fa to your computer and use it in GitHub Desktop.

Select an option

Save mather/6e51cc681807f2ed52fa to your computer and use it in GitHub Desktop.
Scalaで型消去を回避する ref: http://qiita.com/mather314/items/67fdbf8293edc0200444
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
scala> isType[A](new A)
res11: Boolean = true
scala> isType[C](new B)
res12: Boolean = true // 本当は (new B).isInstanceOf[C] => false
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
scala> isType[C](new B)
res13: Boolean = false
import scala.reflect.ClassTag
def isType[T <: A : ClassTag](a: A) = implicitly[ClassTag[T]].runtimeClass.isInstance(a)
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