Kotlin : Single Expression Function

Kotlin is a powerful language that reduced a lot of boilerplate code when compared to Java. The single expression function is the same in terms of reducing the boilerplate code.

The single expression function, as his name suggests, is the function that just has a single expression. We can remove the return type of that function, braces as well as return keyword from it.

This post was originally posted at https://agrawalsuneet.github.io/blogs/kotlin-single-expression-function/ and reposted on Medium on 16th April 2021.

Think about a function that has some calculation to be done based on the passed argument and return the result.

fun convertToFahrenheit(degree : Float) : Float {
return (degree * 9 / 5) + 32
}

println(convertToFahrenheit(degree = 11f))

This can be replaced as

fun convertToFahrenheit(degree : Float) = (degree * 9 / 5) + 32

println(convertToFahrenheit(degree = 11f))

Please continue reading at https://agrawalsuneet.github.io/blogs/kotlin-single-expression-function/

That’s all for now. You can read my other interesting posts here or you can enjoy my games or apps listed here. Feel free to use my open-source Android components in your app listed here. Or drop an email, if you didn’t find what you are looking for and need some help.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store