首页 > 解决方案 > 无法直接从 Scala 中的 for 循环转换迭代器

问题描述

我正在尝试使用带有迭代器的 for 循环来提取案例类的成员字段的所有值并在我的系统中使用,但需要它的格式为Seq[String]. 我想知道为什么会这样:

case class MyClass(field1:String, field2:Int){

  def toSeqString: Seq[String] = {
    val stringIter = for (field <- this.productIterator) yield {
      val changedField = // do some work on 'field'
     changedField.toString
    } 
    // stringIter is of type Iterator[String] at this point
    stringIter.toSeq
  }

}

但这不会:

case class MyClass(field1:String, field2:Int){

  def toSeqString: Seq[String] = {
    for (field <- this.productIterator) yield {
      val changedField = // do some work on 'field'
     changedField.toString
    }.toSeq // have also tried .to[collection.immutable.Seq]
  }

}

错误说第二个示例的结果是 a Iterator[Seq[Char]],而不是 a Seq[String]。为什么我需要将 for 循环的结果提取到 val,而不是直接将其链接到 for-yield 循环的完成?看来我也在做同样的事情?

标签: scala

解决方案


这只是一个括号问题。

你要:

def toSeqString: Seq[String] = {
  (for (field <- this.productIterator) yield {
    val changedField = // do some work on 'field'
   changedField.toString
  }).toSeq
}

注意 . 周围的额外括号for。否则.toSeq应用于块之后yield- 因此制作Stringa Seq[Char]

作为旁注,您可能只想做:

this.productIterator.map(p => ...).toSeq

推荐阅读