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.
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))
There can be another function that has no param passed and just returns something, but that can be replaced with a variable also with or without overriding getter so there is no point.
Still, that function will be called as single expression function.
val name : String = "John"
fun getName() = "John"
Single expression function can be used with any idioms like if-else
, when
, nullable
, operations on the List
, Map
or almost everything.
if-else
fun getResult(percentage : Int) = if (percentage > 40) "Pass" else "Fail"
println(getResult(percentage = 60))
when expression
fun getBaseColorCode(color: String) = when (color) {
"Red" -> 0xff0000
"Green" -> 0x00ff00
"Blue" -> 0x0000ff
else -> throw IllegalArgumentException("Invalid base color")
}
println(getBaseColorCode(color = "Red"))
Collection and its operations
fun getList(divisibleBy : Int) = listOf(1, 2, 3, 4, 5)
.filter{ it -> it%divisibleBy == 0 }
println(getList(divisibleBy = 2))
These are helpfully when need to add small helper functions.