I have a simple class which takes a generic type, Eg:
class SomeClass[T: TypeTag](someVal: T) = {
def value = someVal
def columnType = typeOf[T]
}
I need to check if [T] is Comparable at runtime (I don't want to require that it's comparable, only check if it is or not). If I have an actual instance of [T] (which i don't), I can do the following which works fine...
def canCompareType[T](value: T): Boolean = {
val compClass = classOf[Comparable[_]]
compClass.isAssignableFrom(value.getClass)
}
But I can't work out how to do this with just the type definition and not actually having an instance of [T] available. I've tried the following thinking that it looks and seems reasonable...
def canCompareType[T]: Boolean = {
val compClass = classOf[Comparable[_]]
compClass.isAssignableFrom(classOf[T])
}
But gives the compile error...
Error: class type required but T found : compClass.isAssignableFrom(classOf[T])
I found a similar answer here, but it again assumes that I have an instance of [T] available.
Cast objects to comparable type
Any ideas how I can resolve this. I have a feeling that I must be pretty close.
Update
I need to be able to check also on value types, so I would want canCompareType[Int]
to also return true as 100.compareTo(200)
is valid.
Thanks
Something like this perhaps?
def foo[T: TypeTag] = typeOf[T] match {
case t if t <:< typeOf[Comparable[_]] => "Comparable"
case _ => "Not Comparable"
}