Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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") 
like image 398
uh_big_mike_boi Avatar asked Mar 15 '26 16:03

uh_big_mike_boi


2 Answers

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
like image 129
Jasper-M Avatar answered Mar 18 '26 04:03

Jasper-M


Why you don't use a map function from List(Element) to List(String)?

If you whant to get an Array from List(String) you have the function toArray.