Scala - finding sequence members that are of a certain type's child type -
i have 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 method boommyclassinstances
scala-ish way children
of myclass
, stored in children
arraylist
can call common boom
method upon them all?
my try is:
def boommyclassinstances { children.toarray.map { case mc: myclass => mc.boom } }
is correct approach? pick children of myclass
, right scala way that, or have type bounds?
check out gentraversablelike.collect
. signature traversable[a].collect[b <: a](f: ~> b): traversable[b]
, is, takes collection elements of type a
, partial function f
a
b
, , returns collection of static element-type b
, b
subtype of a
.
val myclassinstances: list[myclass] = children.tolist.collect{case mc: myclass => mc}
since map
expects total function, try above fail scala.matcherror
in case children
not contain instances of myclass
. can work around using option
or flatmap
, collect
seems scala-ish way of achieving want.
Comments
Post a Comment