liveBook · Manning

Conditional logic

As explained in Kotlin in Action, 2E

A Boolean expression is an expression whose evaluation produces a Boolean value.

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

How Kotlin in Action, 2E covers it

How deep it goes
Explains expression values, cascading conditions, block results, smart casts, and when refactoring, stopping short of broader control-flow mechanics.
Examples
Demonstrates maximum selection, numeric assignment, recursive expression evaluation, type-based when branches, and logging during evaluation.
What it assumes
Assumes basic Kotlin functions, parameters, return types, and expressions while introducing value-producing conditionals from familiar Java comparisons.
What you can do after
Apply it via Kotlin if and when expressions to compute values, evaluate typed expression trees, and structure multi-branch logic.
How it connects
Connects conditional logic with expressions, functions, blocks, when expressions, smart casts, exception handling, and Java ternary operators.

Also explained in

Compare how 21 books explain conditional logic →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.