...

/

Single-Expression Functions vs. Functions on All Levels

Single-Expression Functions vs. Functions on All Levels

Explore function types by comparing single-expression and many-level approaches, and understand function levels, parameters, arguments, return types, and varargs.

We'll cover the following...

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.

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
}
...