I'm trying to come up with a generic function that can take primitive data types and also other objects that extends scala.math.Ordering. I checked How to get to type parameters of a reflect.runtime.universe.Type in scala? and I want to get the type of a variable at runtime and I could't get my answer. Example below: import scala.reflect.runtime.universe._ import scala.collection.SortedSet
def getTypeTag[T: TypeTag](obj: T) = typeTag[T]
def createSortedSet[A: TypeTag](y: A) = typeOf[A] match{
//handle the primitive data types
case t1 if t1 =:= typeOf[Int] =>
SortedSet(y)(implicitly[Ordering[Int]].reverse)
case t2 if t2 =:= typeOf[Long] =>
SortedSet(y)(implicitly[Ordering[Long]].reverse)
.....
// last part handle any object that implements Comparable
case tx if tx.getClass.getInterfaces.exists( _.toString == "interface java.lang.Comparable") =>
{// trying to get the type of the variable and then pass in to the Ordering
val TT: Type = getTypeTag(t).tpe
SortedSet(y)(implicitly[Ordering[TT]].reverse)}
case _ => ...
}
so in order to pass in a object and let the Ordering do its job, I need to pass in the type to the Ordering, Say I create a case class that extends Ordering
case class Value(i: Int) extends Ordered[Value] {def compare(that: Value) = this.i - that.i}
val v1 = Value(3)
// now I want to get a SortedSet instance by calling the createSortedSet
createSortedSet(v1)
I got error when I made the above call, so I think reflect.runtime.universe.Type is not really can be used as Type. Is my approach wrong?