1 min read · Updated on by Gabriel Shanahan
Read on to take quick look at looping in Kotlin, specifically for
, while
and do-while
.
for
The for
statement in Kotlin works the same way as the enhanced for
statement in Java.
//sampleStart fun main(args: Array ) { val cakes = listOf("carrot", "cheese", "chocolate") for (cake in cakes) { // 1. println("Yummy, it's a $cake cake!") // 2. } } //sampleEnd
- Loops through each cake in the list.
- We’ll get to string templates (i.e. the
$cake
part) in a bit
You might be wondering how to emulate the classic for
loop, e.g. for(int i = 0; i < 10; i++)
. This can be achieved using the above form in combination with ranges, which we’ll talk about soon.
while
and do-while
The while
and do-while
statements work similarly to most languages as well.
//sampleStart fun eatACake() = println("Eating a Cake!") fun bakeACake() = println("Baking a Cake!") fun main(args: Array ) { var cakesEaten = 0 var cakesBaked = 0 while (cakesEaten < 5) { // 1. eatACake() cakesEaten++ } do { // 2. bakeACake() cakesBaked++ } while (cakesBaked < cakesEaten) } //sampleEnd
- Executes the block while the condition is true.
- Executes the block first and then checks the condition.