Ad space (banner)
๐ŸŽฏKotlin Lessons
Lesson 15 / 68

The if Expression

In this lesson you will learn Kotlin's if expression so you can express a branch concisely on a single line. This is for anyone searching for "Kotlin if expression how to use".

Kotlin has no ternary operator as some languages do, but if itself works as an "expression" that returns a value, so if (condition) valueIfTrue else valueIfFalse takes its place.

The sample code assigns a message to message based on age with the single line if (age >= 20) "Adult" else "Minor". Using the very same keyword both as a statement and as a value-returning expression is characteristic of Kotlin.

A common stumbling block for beginners is the difference between an ordinary if statement and an if expression. They look similar, so a multi-line block with braces and a simple value-returning expression are easy to confuse.

In real-world development the if expression comes up constantly for simple branching, such as assigning a value to a variable or choosing between two messages.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Kotlin directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)