Conditional logic selects a result or action according to a condition. In Kotlin, if is an expression: each branch produces a value, so it can appear directly in an assignment or function body. Kotlin therefore needs no separate ternary operator. section 2.1.2 section 2.3.7
fun max(a: Int, b: Int): Int {
return if (a > b) a else b
}
Return the larger argument by using if as the function result. section 2.1.2
The condition comes first, followed by the true branch and the else branch. For a single expression, Kotlin allows compact syntax. For multiple operations, use a block; its last expression becomes the branch result. section 2.3.7 section 2.3.8
Evaluating an expression tree
fun eval(e: Expr): Int = if (e is Num) e.value else if (e is Sum) eval(e.right) + eval(e.left) else throw IllegalArgumentException("Unknown expression") This cascade checks the expression type, computes a value for recognized cases, and rejects an unknown case. A when expression can make the same multi-choice logic clearer, while preserving smart casts after type checks. section 2.3.7
Use conditional logic effectively by remembering these Kotlin rules:
- Assign an if result directly: val x = if (myBoolean) 3 else 5. section 2.1.2
- Prefer when for several alternatives, including type checks that enable smart casts. section 2.3.7 section 2.6
- Put logging or intermediate calculations in a branch block and leave the returned value as its final expression. section 2.3.8




















