Search code examples
scalafunctional-programmingsuperclass

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?


Solution

  • 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.