Im trying to get the direct super classes / traits of a ClassSymbol. The method baseClasses()
does not work for me as it also includes the super super.. types.
The java.lang.Class.getSuperclass()
and java.lang.Class.getInterfaces()
would actually be sufficient for my use case, but I can't find a way to go from ClassSymbol
to java.lang.Class
in macro context!
If you use macro - you can't obtain runtime-object Class
for class which does not exist (loaded) in compile-time (so you can't have an access to compiling classess from there). But, you could write your own function:
def getDirectBase(a: ClassSymbol) = {
val base = a.baseClasses.toSet - a //`baseClasses` contains `a` itself
val basebase = base.flatMap {
case x: ClassSymbol => x.baseClasses.toSet - x
}
base -- basebase
}
Results (examples obtained using run-time reflection, but compile-time should be same here):
scala> class A
scala> class B extends A
scala> class C extends B
scala> typeOf[C].typeSymbol.asInstanceOf[ClassSymbol].baseClasses
res37: List[reflect.runtime.universe.Symbol] = List(class C, class B, class A, class Object, class Any)
scala> getDirectBase(typeOf[C].typeSymbol.asInstanceOf[ClassSymbol])
res38: scala.collection.immutable.Set[reflect.runtime.universe.Symbol] = Set(class B)