Imagine you’re writing universal domain logic for your program. All I/O is provided via an interface (like UI, persistent storage, networking, etc.), you don’t have to think about it, and you almost don’t care about the platform, on which you run. Your program is fairly simple, only a few straightforward tasks. This chapter describes all essentials you need to write it. The foundational basics that you can build upon: data, processing primitives, and functions to reuse code.
Flow control
Let’s talk logic. The most basic thing you can do to process data or program a behavior is to execute different commands based on a decision. Then you may want to execute the same commands repeatedly over varying inputs – loop – or stop processing early – jump. Branching, loops, and jumps form the foundation of logic programming.
Note: Essentially, all logic can be boiled down to two primitives – branching and jumping, bundled together in different ways. However, when you think about designing an algorithm rather than taking the machine code level perspective, loops emerge as a distinct, fundamental concept. So they have a dedicated topic of their own.
Loops
For-loop
For-loops are only for iterating over sequences (e.g., collections or ranges) in Kotlin.
val loopingCollection = listOf("one", "two", "three")
var loopingResult = ""
for (element in loopingCollection) {
loopingResult += element + ", "
}
loopingResult = ""
for ((index, element) in loopingCollection.withIndex()) {
loopingResult += "$element [$index], "
}
While-loop
var loopingResult = ""
while (loopingResult.isEmpty()) {
loopingResult = "Loops are fun"
}
Do-while-loop
var loopingResult = "Loops are fun"
do {
loopingResult.dropLast(1)
} while (loopingResult.isNotEmpty())