scala - 无法直接从 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 循环的完成?看来我也在做同样的事情?
解决方案
这只是一个括号问题。
你要:
def toSeqString: Seq[String] = {
(for (field <- this.productIterator) yield {
val changedField = // do some work on 'field'
changedField.toString
}).toSeq
}
注意 . 周围的额外括号for
。否则.toSeq
应用于块之后yield
- 因此制作String
a Seq[Char]
。
作为旁注,您可能只想做:
this.productIterator.map(p => ...).toSeq
推荐阅读
- arrays - 迭代列表内的键值对并转换为熊猫数据框
- c# - 如果语句不起作用 Unity C#
- php - xpath 查询 DOMNodeList 对象 ( [length] => 0 )
- python - Python:使用 asyncio 的 Pyppeteer
- angular - Angular Material:mat-nav-list 焦点问题内的 mat-chip
- reactjs - React Redux 处理大数据
- json - 使用 Codable 快速获取 json
- mysql - 运行多线程代码规范时的锁定等待超时
- mongodb - mongodb聚合无序项在Group_id
- php - 如何按计划创建状态检查?API Woocommerce 3+