Get superclasses function in Scala

What would be a short functional way to get the superclasses of a given Class instance in Scala?

All I could come up with is this

def supers(cl: Class[_]): List[Class[_]] = {
  cl :: Option(cl.getSuperclass).map(supers).getOrElse(Nil)
}

Does anyone know a shorter form with some fancy functional constructs?

Answers


Not exactly fancy functional constructs, but (slightly) shorter:

def supers(cl: Class[_]): List[Class[_]] = {
    if (cl == null) Nil else cl :: supers(cl.getSuperclass)
}

scala> class Foo; class Bar extends Foo; class Baz extends Bar
defined class Foo
defined class Bar
defined class Baz

scala> supers(classOf[Baz])
res9: List[Class[_]] = List(class Baz, class Bar, class Foo, class java.lang.Object)

Note that this gives you the class and all of it's superclasses, but then again so does the one provided by the OP.


Need Your Help

How to get phrase tags in Stanford CoreNLP?

nlp stanford-nlp phrase parse-tree

If I want to get phrase tags corresponding each word, how to I get this?

What is a good scripting language for basic file operations?

scripting file productivity cygwin

I often need to copy, move or rename files and directories based on some criteria as I collect data from many resources and I like to keep things organized. What scripting language provides the most

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.