Created
February 3, 2016 14:46
-
-
Save SamirTalwar/86e0a04fd4d47a0b98a2 to your computer and use it in GitHub Desktop.
Print the hierarchy of a given class.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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