Skip to content

Instantly share code, notes, and snippets.

@SamirTalwar
Created February 3, 2016 14:46
Show Gist options
  • Select an option

  • Save SamirTalwar/86e0a04fd4d47a0b98a2 to your computer and use it in GitHub Desktop.

Select an option

Save SamirTalwar/86e0a04fd4d47a0b98a2 to your computer and use it in GitHub Desktop.
Print the hierarchy of a given class.
import scala.collection.SortedSet
sealed trait Tree[T] {
val value: T
}
case class Leaf[T](value: T) extends Tree[T]
case class Node[T](value: T, children: SortedSet[Tree[T]]) extends Tree[T]
object ClassHierarchy {
def main(args: Array[String]) =
printTree(hierarchy(Class.forName(args(0))))
def hierarchy(root: Class[_]): Tree[Class[_]] = {
implicit val ordering = Ordering.by[Tree[Class[_]], String](_.value.getName)
val superclassSet =
if (root.getSuperclass == null)
SortedSet.empty[Tree[Class[_]]]
else
SortedSet(hierarchy(root.getSuperclass))
val interfaces = root.getInterfaces.toSet
Node(root, superclassSet ++ interfaces.map(hierarchy))
}
def printTree(tree: Tree[_], level: Int = 0): Unit = {
println(" " * level + tree.value)
tree match {
case Leaf(_) => Unit
case Node(_, children) => children.foreach(child => printTree(child, level + 1))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment