
In Kotlin, if is used to execute a sequence of instructions (code) if a given conditional expression evaluates to true. Using if with else in Kotlin conditional expressions

You’ll learn about this and more in the following sections. Going back to loops, you can perform an if check on each iteration and terminate the loop at the point where the check evaluates to true. This makes it possible to use them in the same way you would use the ternary operator in other languages, like JavaScript. In that case, the value of the first matching branch becomes the value of the whole expression. In addition, an else block can be nested within both if and when statement to specify an alternative code to run if the condition evaluates to false.īoth if and when can be used as expressions. In Kotlin, the three control statements used to evaluate conditional expressions are if, else, and when.Īn if statement allows you to specify code that should run if a conditional expression evaluates to true, whereas when allows you to specify multiple code branches to run depending on the actual value of a conditional expression. The most common way of achieving this is through the use of conditional expressions inside the loop.Ī conditional expression is one that evaluates to either true or false. When an iteration achieves its purpose - such as finding a given item in a list - it has to be terminated. Technically, you can iterate over anything in a for loop as long as it provides an iterator - like strings, arrays, ranges, and so on. Whatever the case, the for loop allows you to iterate over the collection and sequentially access each individual value in the collection. For example, maybe you want to find a particular item in a list, or you want to multiply each number in an array by two, or you want to get a subset of a string. Oftentimes, you might want to iterate over their values for various reasons. Some examples of these Kotlin data structures include strings, arrays, ranges, and maps. In Kotlin, there are several data structures that could contain a sequence of values. Overview of conditions and loops in Kotlin Using break and continue to control loop execution.


Exploring advanced uses of conditions and loops in Kotlin
