Question

I know that typing is a big deal in Scala, and ideally you go around type casting or any messy solutions by using things like Pattern Matching. However, I can't understand how could I go about it if I am iterating through a list or sequence of items which are a subtype of a common super type, and just want those of a specific subtype in a Sequence of that subtype. I don't think I can put a pattern match in a for-comprehension to achieve this.

So lets say for example I have these classes:

sealed abstract class SuperType
case class SubtypeA extends SuperType
case class SubtypeB extends SuperType

I have a Seq[SuperType] and I want to get a Seq of just the SubtypeA instances, so a Seq[SubTypeA], so that then I can loop through it and execute a method provided by SubTypeA for all elements.

Was it helpful?

Solution

Scala has a function called collect that does exactly what you need. It takes a Partial Function as a parameter and if the Partial Function is defined at the element then it applies it. If it isn't then it skips it. Since matching is essentially a Partial Function we can use this to our advantage:

val list: Seq[SuperType] = ???
val listOfAtypes = list.collect({ case a: SubtypeA => a })

{ case a: SubtypeA => a } is a PartialFunction[SuperType, SubtypeA].

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top