Learn/Kotlin/4. Making decisions
Lesson 4 of 8
Sign in

Kotlin, lesson 4

Making decisions

Programs become useful when they can react differently to different input. To decide, a program asks a yes-or-no question. In Kotlin the answer is a Boolean: true or false.

Comparisons

These operators compare two values and produce a Boolean:

OperatorMeaning
==equal to
!=not equal to
<, <=

2 exercises to try what you just read.

Exercise 1

Cinema tickets

Press Ctrl Enter or Check to test your code.

Exercise 2

Leap year check

Press Ctrl Enter or Check to test your code.

less than, less than or equal
>, >=greater than, greater than or equal

== compares the contents of values, so "cat" == "cat" is true even for two different strings that happen to hold the same text.

if and else

if runs a block only when its condition is true. Add else for the other case, and chain else if to test more conditions in order. Only the first matching branch runs.

if gives back a value

In Kotlin, if is an expression: it produces a value you can store or print. That is why Kotlin has no ? : ternary operator; you don't need one. When you use if as a value, the else branch is required, so there is always an answer.

Combining conditions

  • a && b is true only when both sides are true.
  • a || b is true when at least one side is true.
  • !a flips true to false and back.

Kotlin stops evaluating as soon as it knows the answer. In a && b, if a is false, b is never checked. This is called short-circuiting.

when: many branches, neatly

When you compare one value against several options, when reads much better than a long else if chain. Each branch has a condition, an arrow ->, and what to do. Branches are checked from the top and the first match wins.

You can also write when with no value in parentheses. Then each branch is a full condition, which is the cleanest way to write a chain of unrelated tests:

Like if, when can produce a value. When it does, it must cover every case, which usually means ending with else. The compiler checks this for you, so you never get a missing answer.

Further reading

  • Kotlin docs: Conditions and loops
  • Kotlin docs: Booleans

A cinema prices its tickets by age:

  • under 4: Free
  • 4 to 12: Child: $6
  • 13 to 64: Adult: $11
  • 65 and over: Senior: $7

Read an age (a whole number, 0 or more) and print the matching line exactly.

Sample input:

Sample output:

Hint: inside a Kotlin string, a $ followed by a digit is printed as-is, so "Child: $6" works fine.

A year is a leap year if it is divisible by 4, except years divisible by 100 are not, unless they are also divisible by 400. So 2024 and 2000 are leap years, but 1900 is not.

Read a year and print <year> is a leap year or <year> is not a leap year.

Sample input:

Sample output:

Hint: "divisible by 4" means year % 4 == 0. Combine the rules with &&, || and !.

fun main() {
    val battery = readln().toInt()
    if (battery < 10) {
        println("Plug me in!")
    } else if (battery < 50) {
        println("Running low")
    } else {
        println("All good")
    }
}
val label = if (battery >= 50) "full-ish" else "empty-ish"
val isWeekend = day == "Sat" || day == "Sun"
val canSwim = temperature > 20 && !isRaining
fun main() {
    val dice = readln().toInt()
    val message = when (dice) {
        1 -> "Ouch"
        2, 3, 4 -> "Not bad"          // several values, separated by commas
        in 5..6 -> "Great roll"       // a range of values
        else -> "That's not a die!"
    }
    println(message)
}
val advice = when {
    temperature < 0 -> "Stay inside"
    temperature < 15 && isRaining -> "Take an umbrella and a coat"
    else -> "Enjoy the day"
}
70
Senior: $7
1900
1900 is not a leap year