Kotlin: Control Flow Part 2 — Loops

MJ Manaog
2 min readJul 7, 2020

For

You can use for loop on anything that is iterable and or anything has iterator() function.

  • Line 2 — we created a list using our data class ThePillars
  • Line 8 — we iterate throughout the list, for every element i in the list of thePillars.
  • Line 9 — since we’re referencing the data class ThePillars, we can get its parameters pillar and name
  • Line 13 — is the same as Line 8–11, but we used forEach function instead and the it to reference thePillars.
  • Line 18 — we can also use range using the .. operator. Note that the range is inclusive meaning it includes the start and the endpoint.
  • Line 22 — if we want a descending range, we can also use the downTo keyword.

Other useful operators and keywords:

While

  • Line 2 — we’ve changed our list to arrayListOf to make it mutable
  • Line 9 — we added a new list of pillars
  • Line 13 — we declared a counter
  • Line 14 — here’s how to declare a while loop. Inside the parenthesis () you must declare a conditional statement
  • Line 15 & 16 — while our conditional statement doesn’t return true, the count variable will continue to increment and will also continue to add an item of newListOfPillars to thePillars list.

Do While

  • The only difference between while and do while is that the do while will always first execute the code (inside the {})before evaluating the condition in while() .

Continue & Break

  • continue keyword skips to the next iteration of the innermost containing loop
  • break keyword stops the loop

We’ll talk more about this when we discuss labels

Thanks! :D

--

--