Вопрос

How to do Scala equivalent to this Java code:

int i = 0;
for(String x: xs) {
    for(String y : ys) {
        foo(x, y, i);
        i+=10;
    }
}
Это было полезно?

Решение

There are multiple ways of doing it:

var i = 0                                 
for(x <- xs;y <- ys) {
  foo(x,y,i)
  i = (i+10)
}

To do it functionally without using external i:

xs.foldLeft(0){(a:Int,b) =>
   ys.foldLeft(a){(c:Int, p) =>
     foo(b,p,a)
     c+10
   }
}

Другие советы

You could try this (no mutable variable):

  for(x <- xs.zipWithIndex;y <- ys.zipWithIndex) {
    foo(x._1, y._1, x._2*y._2*10)
  }

You could basically just change the syntax a little.

 var i = 0
    for(x <- xs) {
        for(y <- ys) {
            foo(x, y, i)
            i = i+10
        }
    }
  for (x <- xs; y <- ys; i <- 1 to 10) foo(x, y, i)
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top