2015-06-01 216 views
2

考慮下面的循環,它代表一個「鄰居」For循環繼續

for(x <- -1 to 1; y <- -1 to 1) 
{ 
    // If we are in the current field, just get the one above 
    if((x == 0) && (y == 0)) y = 1 // Problem: Reassignment to val 
} 

,你可以看到,我會得到重新分配,以VAL編譯錯誤。在Java中,我會「繼續」跳過。

這將是一個優雅的解決方案?

回答

6

使用保護:

for (x <- -1 to 1; y <- -1 to 1; if !(x == 0 && y == 0)) { 
    ... 
} 

或者:

for (x <- -1 to 1; y <- -1 to 1 by (if (x == 0) 2 else 1)) { 
    ... 
} 

我第一個想到的是更具可讀性,雖然。