Tutorial by Examples

repeat(10) { i -> println("This line will be printed 10 times") println("We are on the ${i + 1}. loop iteration") }
You can loop over any iterable by using the standard for-loop: val list = listOf("Hello", "World", "!") for(str in list) { print(str) } Lots of things in Kotlin are iterable, like number ranges: for(i in 0..9) { print(i) } If you need an index while...
While and do-while loops work like they do in other languages: while(condition) { doSomething() } do { doSomething() } while (condition) In the do-while loop, the condition block has access to values and variables declared in the loop body.
Break and continue keywords work like they do in other languages. while(true) { if(condition1) { continue // Will immediately start the next iteration, without executing the rest of the loop body } if(condition2) { break // Will exit the loop completely } } ...
//iterates over a map, getting the key and value at once var map = hashMapOf(1 to "foo", 2 to "bar", 3 to "baz") for ((key, value) in map) { println("Map[$key] = $value") }
Looping via recursion is also possible in Kotlin as in most programming languages. fun factorial(n: Long): Long = if (n == 0) 1 else n * factorial(n - 1) println(factorial(10)) // 3628800 In the example above, the factorial function will be called repeatedly by itself until the given conditio...
The Kotlin Standard Library also provides numerous useful functions to iteratively work upon collections. For example, the map function can be used to transform a list of items. val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 0) val numberStrings = numbers.map { "Number $it" } One of...

Page 1 of 1