Search code examples
scalapattern-matchingfor-comprehension

scala pattern matching for comprehension


In scala can you have a for comprehension that iterates through a List of objects and then makes a Arrays of values based on the type of one of the attributes of the elements? So assume I have a list of elements and each element has an attribute, and the attribute could be different types...

for (element <- elementList) element.attribute match {
 case a: Type1 => "Type1"
 case a => "All Types"
}

And then the resulting Array would be an array with values like

Array("Type1", "Type1", "All Types", "Type1", "All Types", "All Types", "All Types", "All Types") 

Solution

  • All you have to do is yield a result... And possibly convert to an Array.

    (for (element <- elementList) yield element.attribute match {
      case a: Type1 => "Type1"
      case a => "All Types"
    }).toArray