Single expressions functions

When the function has a single expression we can remove the curly braces, the same as in Scala, and the function body should be specified after the = symbol. Let's refactor our first function, as follows:

fun greetings(name:String,greeting:String) = greeting + name

We can remove the return keyword, as well. Our function is pretty concise now. We removed return and the type of return as well. As we can see, the code is more readable now. If you want, the return type can be declared too.

Get Spring 5.0 By Example now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.