Expression body
- Kotlin course
- Beginner
- Lesson 73/116
- 5 min
Learn to write expression-body functions with =.
Expression body: short definition with =
Functions that return a single expression can be written shortly with = instead of a block body. fun double(x: Int): Int = x * 2 means the same as fun double(x: Int): Int { return x * 2 }.
fun double(x: Int): Int = x * 2
val result = double(7) // 14In this form return is not written; the right side is returned automatically. The return type can also be inferred: fun double(x: Int) = x * 2.
When to use = vs { }?
For short functions returning a single expression, = is more readable. When the body has multiple statements, a condition or a loop, use the { } block body. Both can give the same result; the choice is a matter of style.
// expression body
fun half(x: Int): Int = x / 2
// block body
fun half(x: Int): Int {
val result = x / 2
return result
}The return type can be inferred in an expression body; in a block body return must be written explicitly.
Practice Write double with an expression body
Define fun double(x: Int): Int = x * 2 (expression body). From main print the result with println(double(7)).
Starter code
fun main() {
// Print the double(7) call with println
}
// Define double with an expression body: x * 2Sample solution
fun main() {
println(double(7))
}
fun double(x: Int): Int = x * 2Expected output
14
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match definition form to role
| Term | Meaning |
|---|---|
fun f() = x |
Expression body |
fun f() { } |
Block body |
: Int |
Explicit return type |
return x |
Return inside a block |
2 Fill in the blank: expression body
fun double(x: Int): Int ____ x * 2
fun double(x: Int): Int = x * 2
Explanation: = x * 2 defines the expression body.
3 What does fun square(x: Int) = x * x return?
- Unit (no return type)
- String
- Throws an exception
- Int (inferred type) Correct answer
Explanation: Even without a written return type, x * x is Int so Int is returned.