Kotlin : Single Expression Function
1 min readApr 16, 2021
--
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))