简体   繁体   English

Scala模式匹配以进行理解

[英]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? 在Scala中,您是否可以具有for理解能力,可以遍历对象列表,然后根据元素属性之一的类型创建值数组? 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将是一个值类似的数组

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

All you have to do is yield a result... And possibly convert to an Array . 您所要做的就是yield结果...并可能转换为Array

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

Why you don't use a map function from List(Element) to List(String) ? 为什么不使用从List(Element)List(String)的映射函数?

If you whant to get an Array from List(String) you have the function toArray . 如果您想从List(String)获取数组,则可以使用toArray函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM