for(iin1..10)// = for (int i = 1; i <= 10; i++)for(iin0until10)// = for (int i = 0; i < 10; i++)for(iin9downTo0)// = for (int i = 9; i >= 0; i--)for(iin0until10step2)// = for (int i = 0; i < 10; i += 2)
如果是数组或者列表,但又必须要用索引,也可以直接来:
123
for(iinarray.indices){println(array[i])// 'i' is the index}
其实有更好的方式:
123
for((index,value)inarray.withIndex()){println("the element at $index is $value")}
funfoo(){listOf(1,2,3,4,5).forEachlit@{if(it==3)return@lit// local return to the caller of the lambda - the forEach loopprint(it)}print(" done with explicit label")}
使用隐式标签,也即遍历的方法当作标签
1234567
funfoo(){listOf(1,2,3,4,5).forEach{if(it==3)return@forEach// local return to the caller of the lambda - the forEach loopprint(it)}print(" done with implicit label")}
使用匿名函数而不是lambda,匿名函数与常规函数体效力一样,所以return只在函数体内生效
1234567
funfoo(){listOf(1,2,3,4,5).forEach(fun(value:Int){if(value==3)return// local return to the caller of the anonymous function - the forEach loopprint(value)})print(" done with anonymous function")}
for(iin0until10){varfound=falsefor(jiniuntil10){if(array[i]+array[j]==target){found=truebreak// only break inner for loop}}if(found){break// this break outer for loop}}