在 Scala 中,当我们使用 for 循环 遍历集合时,可以使用更方便的方法。
for (x <- List){ // statements }
参数
参数 描述 for for 循环使用的关键字。 x 循环变量。 List 要遍历的集合。 statements 每次循环执行的代码逻辑。 说明
以上语法中, List 变量是一个集合,for 循环会迭代所有集合的元素。
案例
for循环集合
使用 for 循环,遍历集合
object HaiCoder { def main(args: Array[String]) : Unit = { println("嗨客网(www.haicoder.net)!\n") var a = 0 val numList = List(1,2,3,4,5,6) // for 循环 for( a <- numList ){ println( "Value of a: " + a ) } } }
程序运行后,控制台输出如下:
我们定义了一个 for 循环结构,并使用了该 for 循环遍历了集合 List。
Scala for循环集合总结
在 Scala 中,当我们使用 for 循环 遍历集合时,可以使用更方便的方法。具体语法为:
for (x <- List){ // statements }