2

据我所知,以下表达式

     for{i <- 0 to 10
         j <- 0 to 10} {...}

等于

  for(i <- 0 to 10) {
     for(j <- 0 to 10) {
        .....
     }
  }

但是,如何将以下表达式转换为第一种情况?

  for(i <- 0 to 10) {
     **execute()**
     for(j <- 0 to 10) {
        .....
     }
  }
4

1 回答 1

5

您可以简单地添加一行,然后运行执行并将结果存储在变量中。例如。:

for{i <- 0 to 10;
    k = doSomethingWith(i);
    j <- 0 to 10} {... do something with any or all of i,j,k ...}

如果执行只是副作用(即返回类型是 Unit),或者您不关心返回值,只需分配给下划线。例如:

for{i <- 0 to 10;
    _ = println(s"i = $i");
    j <- 0 to 10} {... do something with i,j ...}
于 2013-09-10T14:05:34.133 回答