Kotlin Function with Single Expression Tutorial

In this section, we will learn what the single expression function is and how to use it in Kotlin.

Note: we’re assuming you’re already familiar with the Kotlin functions.

What is Single Expression Function in Kotlin?

When working with functions, if the body of that function contains only a single expression, then we can remove the border of the function and essentially turn it into a single expression type of function.

From a functionality point of view, there’s no difference between a typical function and a single expression function.

The main difference is that a single expression function takes shorter space and it’s faster to create one.

How to Declare a Single Expression Function in Kotlin?

Here’s how you can create a single expression function in Kotlin:

fun functionName (parameters):data-type = expression

Note that there’s no pair of braces after the parentheses of the function! We simply put the assignment operator and then comes the expression of the function.

The syntax above is equal to this:

fun functionName(parameters) {

expression

}

Again, note that this type of function only works if the target function has a single expression in it.

Example: declaring a single expression function in Kotlin

fun main(){

    sayHello("John","Doe")

}

fun sayHello (name:String, lastName:String) = println("Hello ${name} ${lastName}")

Output:

Hello John Doe

How does single expression function work in Kotlin?

Here we have the sayHello function declared as a single expression type of function. This is because the function has only one expression in it and that is simply sending a message to the output stream.

Note that there’s no difference in the way we call a single expression or a typical function.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies