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.
Single-expression functions
Many functions in real-life projects just have a single 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.
fun square(x: Double): Double = x * xfun 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.
fun square(x: Double) = x * xfun main() {println(square(10.0)) // 100.0}