Conditions with `if`
Explore Kotlin's conditional control flow by learning how to use if statements effectively. Understand how to apply comparison and logical operators, how Kotlin handles equality differently from Java, and how to write clear, concise conditional code. This lesson prepares you to write complex conditions and sets the foundation for using when statements.
We'll cover the following...
For conditional control flow, Kotlin uses the if and when keywords. The syntax of if-blocks is the same as in C and Java. Similarly, the when keyword is similar to switch in these languages but more powerful, as you will learn.
Conditions using if
Conditions with if can be written as follows:
Each condition is followed by a block of code in curly braces. There can be any number of else-if blocks (including zero) and up to one else-block.
Note: In the else-block, the planet variable is included in the output string using string interpolation. To do so, you just prepend the variable with a
$. More complex expressions must be wrapped with curly braces:"${user.name} logged in".
Equality and Comparison Operators
Kotlin’s operators to formulate conditions are the following:
| Operator | Meaning |
|---|---|
== |
Structural equality ("equals") |
!= |
Structural inequality ("!equals") |
=== |
Referential equality (same memory address) |
!== |
Referential inequality |
> |
Greater than |
< |
Less than |
>= |
Greater or equal than |
<= |
Less than or equal |
Note that the comparison operators work on any Comparable by using its compareTo method.
Note for Java developers: In Kotlin, you use
==where you would useequalsin Java and===where you would use Java’s==.
Logical Operators
To build up more complex conditions from primitive conditions (using the operators above), Kotlin provides the standard logical operators:
| Operator | Meaning |
|---|---|
&& |
Logical “and” |
|| |
Logical “or” |
! |
Logical “not” |
Using these, you can combine multiple primitive conditions:
Quiz
Conditional control flow using if
How would you express the condition “the text is empty or at least 3 characters long”?
text == "" || text.length <= 3
text == "" && text.length >= 3
text == "" || text.length >= 3
text != "" || text.length >= 3
Exercise
Complete the following code snippet to check whether…
- the
agevariable is between 18 and 21 (both inclusive). - the
usernamevariable equals"admin"or"system" - the
numbervariable is equal to neither17nor42.
Summary
- Kotlin’s
ifconditions work the exact same way as in other languages like Java or C. - The logical and comparison operators are also known from some other languages.
- But in contrast to Java, Kotlin offers
==for structural equality and===for referential equality checks.
- But in contrast to Java, Kotlin offers
In the next lesson, you will use the when statement for conditional control flow and learn when to prefer it over if.