Careeroza
Single-Expression Functions
Using = Instead of a Body
Example
When a function just returns one expression, write = expression. The return type can usually be inferred.
fun square(x: Int) = x * x
fun isEven(n: Int) = n % 2 == 0
fun fullName(first: String, last: String) = "$first $last"
fun maxOf3(a: Int, b: Int, c: Int) = maxOf(a, maxOf(b, c))
fun gstOf(amount: Int): Int = amount * 18 / 100
fun main() {
println(square(9))
println(isEven(10))
println(fullName("Virat", "Kohli"))
println(maxOf3(4, 19, 7))
println(gstOf(1000))
}Output
81 true Virat Kohli 19 180
Combining with when and if
Example
Single-expression functions pair nicely with if and when expressions.
fun signOf(n: Int) = when {
n > 0 -> "positive"
n < 0 -> "negative"
else -> "zero"
}
fun ticketPrice(age: Int) = if (age < 12) 100 else 200
fun main() {
println(signOf(-4))
println(signOf(0))
println(ticketPrice(8))
println(ticketPrice(30))
}Output
negative zero 100 200
Note: Write the return type explicitly for public functions in libraries, so a change in the body does not silently change the API.