DEV Community

Roel Tombozafy
Roel Tombozafy

Posted on

Kotlin fundamentals Part II: conditions

When you write your code, sometimes you need to check any conditions in order to change the value of a variable or something else. Like other programming language, Kotlin supports conditions with the if instruction

Let's imagine that in our code, we ask the user to input his age. Based on the age, we will display a message: if age is greater than 18 then we output "Adult", if not "Teenager"

prtint("Enter your age: ")
val age = readLine()

if (age > 18) {
    println("Adult")
} else {
    println("Teenager")
}
Enter fullscreen mode Exit fullscreen mode

Sometimes we need to check more than one condition, in that case we use the if else instruction

println("Enter a country code: ")
val countryCode = readLine()

if (countryCode == "MG") {
    println("Madagascar")
} else if (countryCode == "US") {
    println("United States")
} else {
    println("Unknown country")
}
Enter fullscreen mode Exit fullscreen mode

Evaluate multiple values with when

Suppose that we assign a variable capital based on the value of country, we can use if statement to do that but in this case we are a testing the same value multiple times. We'd better use when

val capital: String? // the variable can be null

when(country) {
    "Madagascar" -> capital = "Antananarivo"
    "Spain" -> capital = "Madrid"
    else -> capital = "Unknown"
}
Enter fullscreen mode Exit fullscreen mode

The code above can be written as

// we directly store the return value of when in a variable
val capital = when(country) {
    "Madagascar" -> "Antananarivo"
    "Spain" -> "Madrid"
    else -> "Unknown"
}
Enter fullscreen mode Exit fullscreen mode

In some case we may check for a multiple value in the when statement

when(country) {
    "France", "Spain", "Germany" -> println("Europe")
    "Ghana", "Mali", "Egypt" -> println("Africa")
    else -> println("Somewhere else")
}
Enter fullscreen mode Exit fullscreen mode

We can also use range in the when statement

val number = 42
when (number) {
    in 1..39 -> println("Not yet")
    in 40..45 -> println("Close enough")
    else -> println("Out of range")
}
Enter fullscreen mode Exit fullscreen mode

If there are mutiple statements to execute when a certain conidition is matched, we can use the braces {}

val number = 42
when (number) {
    in 1..39 -> println("Not yet")
    in 40..45 -> println("Close enough")
    else -> { println("Out of range")
              println("Definitely not")
            }
}
Enter fullscreen mode Exit fullscreen mode

That's all for today's article. See you in the next where we are going to talk about functions in kotlin.

Top comments (0)