An expression body makes a Kotlin function concise by placing one expression after = instead of using braces and an explicit return. It suits trivial operations and functions whose single expression is an if, when, or try expression. section 2.1.3
A concise maximum function
fun max(a: Int, b: Int): Int = if (a > b) a else b The if expression supplies the result directly. Kotlin can also infer the return type: fun max(a: Int, b: Int) = if (a > b) a else b Type inference here does not remove typing; the compiler derives the function’s return type from the expression. section 2.1.3
Use expression bodies in several Kotlin patterns:
- Return a when expression directly, including multiline branch logic such as mapping enum colors to mnemonic words. section 2.3.2
- Replace an if cascade with a compact expression body; when can make multiple choices or type-based evaluation clearer. section 2.3.7
- Define a computed property getter, such as val isSquare get() = height == width, while keeping property access unchanged. section 2.2.2
- Keep compound actions inside a when branch block; the block’s last expression becomes that branch’s result. section 2.3.8
Expression bodies differ from block bodies: a block-bodied function that returns a value requires an explicit return type and return statements. Within if or when branch blocks, however, the final expression supplies the branch result. IntelliJ IDEA and Android Studio can convert between the two styles through an intention action. section 2.1.3 section 2.3.8
