I have the following situation:
Java lib class:
class LibClass {
ArrayList<LibClass> children;
}
my program Scala code:
abstract class MyClass extends LibClass {
def boom { }
def boomMyClassInstances // ???
}
class Lala extends MyClass
class Hoho extends MyClass
The question is: in the method boomMyClassInstances what is the most Scala-ish way to get all the children of MyClass, stored in the children ArrayList so that I can call the common boom method upon them all?
My try is:
def boomMyClassInstances {
children.toArray.map { case mc: MyClass => mc.boom }
}
Is this a correct approach? Will it pick all the children of MyClass and this is the right Scala way for that, or do I have to say something about type bounds?
Check out
GenTraversableLike.collect. Its signature essentially isTraversable[A].collect[B <: A](f: A ~> B): Traversable[B], that is, it takes a collection with elements of typeAand a partial functionffromAtoB, and returns a collection of static element-typeB, whereBis a subtype ofA.Since
mapexpects a total function, your try above will fail with anscala.MatchErrorin casechildrendoes not only contain instances ofMyClass. You can work around this by usingOptionorflatMap, butcollectseems to be the most Scala-ish way of achieving what you want.