Scala for-comprehension 语法

标签 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)
}

Scala 语法中是否有任何方法可以使用 stringWithIndex拆分为部分(字符串和索引)for领悟标题 ,这样代码的读者就不必对 stringWithIndex._1 的值感到疑惑。和 stringWithIndex._2 ?

我尝试了以下操作,但无法编译:
for (case (string, index) <- strings.zipWithIndex) {
  // Do something with string and index
}

最佳答案

你几乎明白了:

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

看,不需要 case关键词。

关于Scala for-comprehension 语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4933697/

相关文章:

Scala:如何在未来打印列表

scala - 将至强融核与基于 JVM 的语言结合使用

Scala - 如果存在,则删除文件,Scala 方式

python - 将元组添加到列表中而不让它们获得引号?

python元组和枚举

c++ - 如何通过地址获取元组中元素的索引?

Scala 函数接受一个映射,修改值并返回一个映射

scala - _ 必须遵循方法

scala - "close"一个流?

scala - 与 FlatMap/Map 转换的 for 理解相混淆