liveBook · Manning

Expression body

As explained in Kotlin in Action, 2E

An expression body is a Kotlin function body consisting of a single expression written after an equals sign instead of a block and explicit return statements.

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

How Kotlin in Action, 2E covers it

How deep it goes
Explains syntax, inferred return types, conditional and when expressions, branch blocks, and conversion from block bodies.
Examples
Uses maximum selection, enum-color mnemonics, expression evaluation, logging branches, and a Rectangle squareness property.
What it assumes
Assumes basic Kotlin functions and types while teaching expression results, return-type inference, and block-body distinctions.
What you can do after
Apply expression bodies to write concise functions and computed getters, then refactor between if, when, and block-based forms.
How it connects
Connects expression bodies with type inference, if expressions, when expressions, custom accessors, smart casts, and Java interoperability.

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.