我有简单的scala代码:
object CollectionSnippets extends App {
var closureVal = 0
def lineNum(s:String) : String = {
closureVal = closureVal + 1;
closureVal.toString + "." + s;
}
val list1 = List("aline","aline","aline")
val list2 = list1.map(lineNum)
list2.foreach(println)
}
问题是我正在改变变量,我觉得这不是正确的做法。
你能建议我一个更好的方法吗?
答案 0 :(得分:5)
您可以使用zipWithIndex
。
scala> list1.zipWithIndex.map(t => t._2 + ": " + t._1)
res0: List[String] = List(0: aline, 1: aline, 2: aline)
scala> res0.foreach(println(_))
0: aline
1: aline
2: aline
答案 1 :(得分:3)
考虑一下,
list1 zip Stream.from(1) foreach { x => println(x._2 + "." + x._1) }
然而,对于整洁的整合,请考虑
implicit class RichLiner[A](val a: List[A]) extends AnyVal {
def liner(sep: String = ".") =
a zip Stream.from(1) foreach { x => println(x._2 + sep + x._1) }
}
等等
scala> list1.liner()
1.aline
2.aline
3.aline
<强>更新强>
最佳选择是使用Iterator.from(1)
(注意评论和想法,感谢@ om-nom-nom),例如如下,
list1.iterator zip Iterator.from(1) foreach { it => println(it._2 + "." + it._1) }
1.aline
2.aline
3.aline