The if expression

The if expression is used to make a logical decision based on the fulfillment of a condition. We make use of the if keyword to write if expressions:

val a = 1if (a == 1) { print("a is one")} 

The preceding if expression tests whether the a == 1 (read: a is equal to 1) condition holds true. If the condition is true, the a is one string is printed on the screen, otherwise nothing is printed.

An if expressions often has one or more accompanying else or else if keywords. These accompanying keywords can be used to further control the flow of a program. Take the following if expression for example:

val a = 4if (a == 1) {  print("a is equal to one.")} else if (a == 2) {    print("a is equal to two.")} else {    print("a is neither one ...

Get Kotlin Programming By Example now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.