jeudi 8 juin 2017

How to get the runtime class of a generic type in Scala?

import scala.reflect.runtime.universe._
import scala.reflect.ClassTag
import scala.reflect.classTag

def getTypeTag[T: TypeTag](obj: T) = println(typeTag[T].tpe)

class Entity
{
    def greet = println("Hello!")
}

class Point[T : TypeTag](val x : T, val y :T) extends Entity

val p = new Point[Int](2,5)
val p2 = new Point[Float](1.0f,-5.0f)
val p3 = new Point[Double](4.0,-7.0)

val path = Array[Entity](p,p2,p3)

path.foreach(getTypeTag(_))

This small code snippet writes to stdout

Helper.this.Entity
Helper.this.Entity
Helper.this.Entity

I'd like to write

Helper.this.Point[Int]
Helper.this.Point[Float]
Helper.this.Point[Double]

I know there are already a lot of question about scala reflection, I read many of them but still haven't understood the difference between TypeTag, Manifest and ClassTag; nor I can get this very basic example to work. Any help would be greatly appreciated.

Thanks in advance





Aucun commentaire:

Enregistrer un commentaire