Ral*_*lph 7 scala tuples for-comprehension
在下面的代码中,在for理解中,我可以使用元组取消引用来引用字符串和索引:
val strings = List("a", "b", "c")
for (stringWithIndex <- strings.zipWithIndex) {
// Do something with stringWithIndex._1 (string) and stringWithIndex._2 (index)
}
Run Code Online (Sandbox Code Playgroud)
有没有在斯卡拉语法的方式有stringWithIndex拆分成零件(串和索引)的范围内for理解头,使代码的读者不必在值怀疑stringWithIndex._1和stringWithIndex._2?
我尝试了以下,但它不会编译:
for (case (string, index) <- strings.zipWithIndex) {
// Do something with string and index
}
Run Code Online (Sandbox Code Playgroud)
ped*_*rla 21
你几乎得到了它:
scala> val strings = List("a", "b", "c")
strings: List[java.lang.String] = List(a, b, c)
scala> for ( (string, index) <- strings.zipWithIndex)
| { println("str: "+string + " idx: "+index) }
str: a idx: 0
str: b idx: 1
str: c idx: 2
Run Code Online (Sandbox Code Playgroud)
看,不需要case关键字.
小智 7
strings.zipWithIndex.foreach{case(x,y) => println(x,y)}
Run Code Online (Sandbox Code Playgroud)
RES:
(a,0)
(b,1)
(c,2)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2857 次 |
| 最近记录: |