Skip to main content

Kotiln - Control Flow - If

Greetings!

If is the most basic way to control flow in Kotlin. Unlike Java, in Kotlin if is an expression. That is it return a value.
  • Statement - is a program instruction that return no value. Can't be on right side of the equal sign.
  • Expression - is a program instruction that return values. Can be assign to a variable.

Java

private void findMax(int a, int b) {
    int max;
    if (a > b) {
        max = a;
    } else {
        max = b;
    }
    System.out.println("Max value is " + max);
}

Kotlin (traditional statement)

private fun findMax(a: Int, b: Int) {
    val max: Int
    if (a > b) {
        max = a
    } else {
        max = b
    }
    println("Max value is $max")
}


Kotlin (as an expression)

private fun findMax(a: Int, b: Int) {
    val max: Int = if (a > b) {
        a
    } else {
        b
    }
    println("Max value is $max")
}


Ternary Operator

Kotlin doesn't have a ternary operator. It's because result of if, else can be assigned to a variable.

Java
private void findMax2(int a, int b) {
    String result = (a > b) ?  a + " is greater than " + b : b + "is greater than " + a;
    System.out.println(result);
}

Kotlin
private fun findMax2(a: Int, b: Int) {
    val result = if (a > b) "$a is greater than $b" else " $b is greater than $a"
    println(result)
}

Return it

private fun directReturn(age: Int): String {
    return if (age < 21) "You are a kid" else "You are an adult"
}


Comments