Search⌘ K
AI Features

Single-Expression Functions vs. Functions on All Levels

Explore the different ways to define functions in Kotlin including single-expression functions that simplify returns, top-level functions for utilities, member functions inside classes, and local functions nested within other functions. Understand parameters, the Unit return type, and the use of vararg for flexible argument handling to write clean and efficient Kotlin code.

Single-expression functions

Many functions in real-life projects just have a single expressionAs a reminder, an expression is a part of our code that returns a value., so they start and immediately use the return keyword. The square function defined below is a great example. For such functions, instead of defining the body with curly braces, we can use the equality sign (=) and just specify the expression that calculates the result without specifying return. This is single-expression syntax, and functions that use it are called single-expression functions.

Kotlin 1.5
fun square(x: Double): Double = x * x
fun main() {
println(square(10.0)) // 100.0
}

An expression can be more complicated and take multiple lines. This is fine as long as its body is a single statement.

Kotlin 1.5
fun findUsers(userFilter: UserFilter): List<User> =
userRepository
.getUsers()
.map { it.toDomain() }
.filter { userFilter.accepts(it) }

When we use single-expression function syntax, we can infer the result type. We don’t need to, but we can, even though explicit result types might still be useful for safety and readability.

Kotlin 1.5
fun square(x: Double) = x * x
fun main() {
println(square(10.0)) // 100.0
}
...