I am trying to answer practice question from Book "Scala for Impatient 2nd Edition". The question is like this :
Look at the
BitSet
class, and make a diagram of all its superclasses and traits.Ignore the type parameters (everything inside the […]).Then give the linearization of the traits.
The first impression I am thinking of is to get all BitSet
's superclasses/traits in a List.
To recursively get superclasses for a given class, I am managing to use below snippet
def recurGetSupers(cls: Class[_]): List[Class[_]] = {
cls :: Option(cls.getSuperclass).map(recurGetSupers).getOrElse(Nil)
}
However, using above snippet will not give me a List of class, as expected, but below :
scala> recurGetSupers(classOf[scala.collection.BitSet])
res0: List[Class[_]] = List(interface scala.collection.BitSet)
So, my question is how to get superclasses or trait for the given trait ?
Scala traits correspond to Java interfaces. So to get them you need the getInterfaces
method. In Scala terms, it returns an Array[Class[_]]
which will get implicitly converted to a Seq
and you can call toList
on it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.