Search code examples
scalascala-reflectscala-generics

Reflection on type members?


I know this is possible:

import scala.reflect._

trait Foo[A]

def isDouble[A: ClassTag](foo: Foo[A]) = classTag[A].runtimeClass == classOf[Double]

object Foo1 extends Foo[Double]
object Foo2 extends Foo[String]
assert(isDouble(Foo1))
assert(!isDouble(Foo2))

But, now I want to make the A an abstract type:

import scala.reflect._

trait Foo {
  type A
}

def isDouble(foo: Foo): Boolean = ???

object Foo1 extends Foo {override type A = Double}
object Foo2 extends Foo {override type A = String}
assert(isDouble(Foo1))
assert(!isDouble(Foo2))

How do I implement the isDouble function?


Solution

  • Scala let's you refer the arguments to the left of a curried function (in this case foo):

    def isDouble(foo: Foo)(implicit ev: ClassTag[foo.A]) = classTag[foo.A].runtimeClass == classOf[Double]