Efficient iteration with index in Scala

前端 未结 12 549
后悔当初
后悔当初 2020-12-12 11:57

Since Scala does not have old Java style for loops with index,

// does not work
val xs = Array(\"first\", \"second\", \"third\")
for (i=0; i<         


        
12条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-12 12:22

    Looping in scala is pretty simple. Create any array of your choice for ex.

    val myArray = new Array[String](3)
    myArray(0)="0";
    myArray(1)="1";
    myArray(2)="2";
    

    Types of loops,

    for(data <- myArray)println(data)
    
    for (i <- 0 until myArray.size)
    println(i + ": " + myArray(i))
    

提交回复
热议问题