AnyCompiler

Operators and Control Flow

In Kotlin, if isn't just a statement — it's an expression that produces a value. That means you can assign the result of an if/else directly to a variable, with no separate ternary operator needed the way Java and C# have one.

fun main() {
    val score = 73
    val result = if (score >= 60) "pass" else "fail"
    println(result)
    for (i in 1..3) {
        print("$i ")
    }
    println()
}
Output
pass
1 2 3 

1..3 is a range — for (i in 1..3) iterates from 1 through 3 inclusive, with no separate index variable or condition to manage like a classic C-style for loop.

Next: functions — fun syntax, parameters, default arguments, and single-expression functions.

Practice exercise

Set a val score to 73. Using if as an expression, print "pass" if score is 60 or above, otherwise "fail".