Efficient iteration with index in Scala

前端 未结 12 564
后悔当初
后悔当初 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条回答
  •  旧时难觅i
    2020-12-12 12:14

    I have the following approaches

    object HelloV2 {
    
       def main(args: Array[String]) {
    
         //Efficient iteration with index in Scala
    
         //Approach #1
         var msg = "";
    
         for (i <- args.indices)
         {
           msg+=(args(i));
         }
         var msg1="";
    
         //Approach #2
         for (i <- 0 until args.length) 
         {
           msg1 += (args(i));
         }
    
         //Approach #3
         var msg3=""
         args.foreach{
           arg =>
            msg3 += (arg)
         }
    
    
          println("msg= " + msg);
    
          println("msg1= " + msg1);
    
          println("msg3= " + msg3);
    
       }
    }
    

提交回复
热议问题