Multiconditional Loop in Kotlin
Last Updated :
23 Jan, 2022
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:
Kotlin
import java.io.*;
class GFG {
public static void main (String[] args) {
int [] data = {5, 6, 7, 1, 3, 4, 5, 7, 12, 13};
for (int i=0; i<10 && i < data[i];i++) {
System.out.println (data[i]);
}
}
}
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
Example
The preceding multiconditional loop can be written in Kotlin like so:
Kotlin
(0..9) .asSequence ( ) .takeWhile {
it<numbers [it]
}.forEach
println( "$it - ${data[it]}")
}
It's nice, clean, and definitely not an eyesore.
- We used takeWhile, which returns a sequence containing the first elements satisfying the given predicate (in this case, i <data [i]).
- Though takewhile returns the first elements that satisfy the given predicate, you might be tempted to think that it will first evaluate the complete range and then pass to forEach.
- That would have been the case if we hadn't used .asSequence (). We converted the range to a Sequence<T>, and because of this, it was lazily evaluated. In short, it won't process the whole set of items with .takeWhile { ... } and will only check them one by one when .forEach { . . . }is up to process the next item.
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:
Kotlin
(0..9).takeWhile {
println{"inside takewhile"}
it<numbers[it]
}.forEach
println( "inside forEach")
}
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:
Kotlin
(0..9).asSequence().takewhile {
printin ("Inside takewhile")
it <numbers[it]
}.forEach{
printin ("Inside forEach")
}
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.
Similar Reads
"lateinit" Variable in Kotlin In Kotlin, there are some tokens that cannot be used as identifiers for naming variables, etc. Such tokens are known as keywords. In simple words, keywords are reserved and have special meaning to the compiler, hence they can't be used as identifiers. For example, asbreakclasscontinuelateinit "latei
3 min read
Multiple Return Values in Kotlin Kotlin is a statically typed, general-purpose programming language developed by JetBrains, that has built world-class IDEs like IntelliJ IDEA, PhpStorm, App code, etc. It was first introduced by JetBrains in 2011 and is a new language for the JVM. Kotlin is an object-oriented language, and a âbetter
3 min read
Kotlin do-while loop Like Java, the do-while loop is a control flow statement that executes a block of code at least once without checking the condition, and then repeatedly executes the block, or not, depending on a Boolean condition at the end of the do-while block. It contrasts with the while loop because the while l
2 min read
Kotlin while loop In programming, loop is used to execute a specific block of code repeatedly until certain condition is met. If you have to print counting from 1 to 100 then you have to write the print statement 100 times. But with help of loop you can save time and you need to write only two lines.While loopIt cons
2 min read
What is Kotlin Multiplatform? Kotlin Multiplatform or KMP is a technology that allows you to write code once and run it anywhere natively. This native feature motivates developers to prefer KMP over other cross-platform frameworks. KMP supports mobile operating systems such as Android and IOS, web, and desktop operating systems
5 min read
Kotlin Tutorial This Kotlin tutorial is designed for beginners as well as professional, which covers basic and advanced concepts of Kotlin programming language. In this Kotlin tutorial, you'll learn various important Kotlin topics, including data types, control flow, functions, object-oriented programming, collecti
4 min read
Triple in Kotlin In programming, we call functions to perform a particular task. The best thing about function is that we can call it any number of times and it returns some value after computation i.e. if we are having add() function then it always returns the sum of both the numbers entered. But, functions have so
4 min read
Kotlin Collection Write operations Collection Write operations are used to change the content of MutableCollection. MutableCollection is defined as the Collection with write operations like add and remove. Operations supported are as follows: Adding elements Removing elements and Updating elements Addition of elements - add() functio
4 min read
Kotlin Reflection Reflection is a set of language and library features that provides the feature of introspecting a given program at runtime. Kotlin reflection is used to utilize class and its members like properties, functions, constructors, etc. at runtime. Along with Java reflection API, Kotlin also provides its o
3 min read
Pair in Kotlin In programming, we call functions to perform a particular task. The best thing about function is that we can call it any number of times and it return some value after computation i.e. if we are having add() function then it always returns the sum of both the numbers entered. But, functions has some
3 min read