Single expression functions

Single expression functions are means of reducing boilerplate when writing functions in Kotlin, by allowing us to remove the curly braces and define a function as a single expression. To demonstrate the usage of single expression functions, we'll start with the following simple logMessage function:

fun logMessage(msg: String) {
println(msg)
}

This function body is a single simple line. Kotlin allows us to rewrite this function using a single expression function like the following:

fun logMessage(msg: String) = println("")

To make a function a single expression function, we can add the = operator after the closing parentheses and then define the expression to use as the function implementation. The same is possible for functions that have a non-unit return type. In this example, we've defined a getPrompt function that returns String:

fun getPrompt() : String {
return "Hello. How are you?"
}

This getPrompt function can be simplified to a single expression function like so:

fun getPrompt() : String = "Hello. How are you?"

In this updated implementation, the String literal "Hello, How are you?" follows the = operator and defines what the return value should be. In fact, in cases like this, where the return type can be inferred by the compiler, we can simplify the implementation even further.

In this case, the right-hand side of = is String, so the compiler can infer the return type of getPrompt as a String type:

fun getPrompt() = "Hello. How are you?"

Single expression functions are a common Kotlin idiom as they reduce boilerplate and make simple functions very easy to read and understand. In the next section, we'll explore a more interesting type of function: infix functions.