2017-06-04 42 views
0

在標籤返回爲什麼這個代碼不從ints2.forEach回來,但每次都將輸出level 1 xx ====? 並沒有區別,當我[email protected]設置標籤ints2.forEach爲什麼這個代碼是不是在科特林

fun foo() { 
    val ints = Array(5, {i->i}) 
    ints.forEach [email protected] { 
     println("level 1 $it ====") 
     val ints2 = Array(3, {i->i}) 
     ints2.forEach { 
      if (it == 2) [email protected] 
      println("level 2 $it") 
     } 
    } 
} 

fun main(args: Array<String>) { 
    foo() 
} 
+0

可以粘貼預期的輸出?我完全不瞭解你的問題 – harshavmb

回答

2

爲什麼這個代碼不從ints.forEach返回,將輸出 「1級XX ====」 多少次?

通過返回標籤(@let在您的情況下),它僅從forEach內部的lambda表達式返回。因此,你的foo()相當於下面的代碼(使用匿名函數,而不是標籤)。這就是爲什麼forEach塊仍然會爲數組中的每個值執行。你可以找到更多的細節here

fun foo() { 
    val ints = Array(5, {i->i}) 
    ints.forEach(fun(it: Int) { 
     println("level 1 $it ====") 
     val ints2 = Array(3, {i->i}) 
     ints2.forEach { 
      if (it == 2) return 
      println("level 2 $it") 
     } 
    }) 
} 

而且沒有差異,當我的標籤 「讓@」 設置爲 ints2.forEach。如上

同樣的道理。通過settng @let標籤ints2.forEach,該內forEach塊仍然it == 2之前執行兩次。