【问题标题】:scala pattern matching for comprehension用于理解的 scala 模式匹配
【发布时间】:2018-03-26 09:04:04
【问题描述】:

在 scala 中,您能否有一个 for 理解,它遍历对象列表,然后根据元素的属性之一的类型创建一个值数组?所以假设我有一个元素列表,每个元素都有一个属性,并且属性可以是不同的类型......

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

然后生成的 Array 将是一个具有类似值的数组

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

【问题讨论】:

  • 问题是什么?
  • 我写的东西不起作用。问题是如何制作数组

标签: scala pattern-matching for-comprehension


【解决方案1】:

您所要做的就是yield 一个结果...并可能转换为Array

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

【讨论】:

    【解决方案2】:

    为什么不使用从List(Element)List(String) 的映射函数?

    如果你想从List(String) 获取一个数组,你有函数toArray

    【讨论】:

    • 所以这只是:elementList map { _.attribute match { /* cases */ } }.toArray,对吧?
    猜你喜欢
    • 2019-10-02
    • 2016-05-17
    • 2021-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-31
    • 2014-09-30
    • 1970-01-01
    相关资源
    最近更新 更多