Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Scala reflection to find most derived runtime type

I'm trying to use Scala 2.10 reflection to find the most derived type of a method argument. For example, consider this program:

import reflect.runtime.universe._

object ReflectionTest {

  def checkType[A : TypeTag](item: A) {
    println("typeOf[A]: " + typeOf[A])
  }

  def main(args: Array[String]) {
    val a = Array(1, "Hello")
    for (item <- a) checkType(item)
  }
}

Here a has type Array[Any] so each item being sent to checkType has type Any. As a result, checkType outputs

typeOf[A]: Any
typeOf[A]: Any

This makes sense to me since the TypeTag is generated by the compiler at the point of the call (where all it knows about the type is that it is Any). What I want, however, is to determine the actual type of each item. I'd like output something along the lines of

Int
String

I have looked over the documentation here

http://docs.scala-lang.org/overviews/reflection/overview.html

but the samples don't seem to cover this case and I find the discussion there of Environments, Universes, and Mirrors difficult to penetrate. It seems like what I'm trying to do should be fairly simple but perhaps I'm approaching it completely wrong.

like image 726
Peter C. Chapin Avatar asked Nov 17 '25 10:11

Peter C. Chapin


1 Answers

Most obvious solution would be to use the class:

def checkType[A](item: A) {
  println("typeOf[A]: " + item.getClass)
}

But if you want to work with Type, then some additional work is needed:

def checkType[A](item: A) {
  val mirror = runtimeMirror(this.getClass.getClassLoader)
  println("typeOf[A]: " + mirror.classSymbol(item.getClass).toType)
}
like image 177
tenshi Avatar answered Nov 19 '25 10:11

tenshi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!