官术网_书友最值得收藏!

Loops

Kotlin supports the usual duo of loop constructs found in most languages—the while loop and the for loop. The syntax for while loops in Kotlin will be familiar to most developers, as it is exactly the same as most C-style languages:

    while (true) { 
      println("This will print out for a long time!") 
    } 

The Kotlin for loop is used to iterate over any object that defines a function or extension function with the name iterator. All collections provide this function:

    val list = listOf(1, 2, 3, 4) 
    for (k in list) { 
      println(k) 
    } 
 
    val set = setOf(1, 2, 3, 4) 
    for (k in set) { 
      println(k) 
    } 

Note the syntax using the in keyword. The in operator is always used with the for loops. In addition to collections, integral ranges are directly supported either inline or defined outside:

    val oneToTen = 1..10 
    for (k in oneToTen) { 
      for (j in 1..5) { 
        println(k * j) 
       } 
    } 
Ranges are handled in a special way by the compiler, and are compiled into index-based for loops that are supported directly on the JVM, thus avoiding any performance penalty from creating iterator objects.

Any object can be used inside a for loop provided that it implements a function called iterator , making this an extremely flexible construct. This function must return an instance of an object that provides the following two functions:

  • The fun hasNext(): Boolean operator
  • The fun next(): T operator

The compiler doesn't insist on any particular interface, as long as the object returned has those two functions present. For example, in the standard String class, Kotlin provides an iterator extension function that adheres to the required contract, and so strings can be used in a for loop to iterate over the individual characters:

    val string = "print my characters" 
    for (char in string) { 
      println(char) 
    } 

Arrays have an extension function called indices, which can be used to iterate over the index of an array:

    for (index in array.indices) { 
      println("Element $index is ${array[index]}") 
    }
The compiler also has special support for arrays, and will compile a loop over an array to a normal index-based for loop, avoiding any performance penalty just like for range loops.
主站蜘蛛池模板: 兴宁市| 铜梁县| 崇信县| 铁岭市| 砀山县| 塘沽区| 时尚| 桑日县| 武城县| 巴彦淖尔市| 辽阳县| 保定市| 车险| 满城县| 竹山县| 呼和浩特市| 台南市| 大宁县| 凯里市| 寿光市| 卫辉市| 嘉黎县| 如东县| 阳城县| 三明市| 白银市| 丁青县| 贡觉县| 什邡市| 辛集市| 策勒县| 涞源县| 休宁县| 拜泉县| 威海市| 澜沧| 清水县| 安康市| 施秉县| 崇仁县| 西乌珠穆沁旗|