![]() |
VOOZH | about |
As we all know about loops, in Kotlin, loops are compiled down to optimized loops wherever possible. For example, if you iterate over a number range, the bytecode will be compiled down to a corresponding loop based on plain int values to avoid the overhead of object creation. Conditional loops are common to any programming language you pick. If you apply multiple conditions to a loop, it is called a multiconditional loop. A simple example of a multiconditional loop in Java is illustrated here:
The preceding code on execution will print out 5, 6, and 7. Let's see how we can use a multiconditional loop in Kotlin. We will be looking at a functional approach to the same thing in Kotlin
The preceding multiconditional loop can be written in Kotlin like so:
It's nice, clean, and definitely not an eyesore.
First, we will work with an eager evaluation over Iterable<T>. This is the eager version, which evaluates the first function before moving on to the next one:
Output:
Inside takeWhile Inside takeWhile Inside takeWhile Inside takewhile Inside forEach Inside forEach Inside forEach
As you can see, the range was first processed with takewhile (which returned 0, 1, 2) and was then sent for processing to forEach. Now, let's see the lazy version:
Output:
Inside takewhile Inside forEach Inside takewhile Inside forEach Inside takewhile Inside forEach Inside takewhile
As you can see in the preceding example, takewhile is evaluated only when forEach is used to process an item. This is the nature of Sequence<T>, which performs lazily where possible.