Higher Order Functions in Kotlin
Sep 2, 2018 · 1 min read
When we say a function is higher oder it at-least has one of these
- it should accept a function as an argument
- returns function as a result
As a primary thing, Kotlin supports for Higher order functions
Let’s get into the code
In this code, getCoffeePrice() accept function as an argument
and getOffer() returns a function as a result
class Coffee(val coffeName: String, val cost: Double) {
private val gst = 0.6
fun getCoffeePrice(offer: (Double) -> Double): Double {
return offer(cost) + gst
}
fun getOffer(code: String): (Double) -> Double = when (code) {
"1OFF" -> { it -> it - 10 }
else -> { it -> it }
}
}
fun main(args: Array<String>) {
val coffee = Coffee("LongBlack", 6.00)
println("--- Coffee cost ---- ${coffee.getCoffeePrice(coffee.getOffer("1OFF"))}")
}Happy coding :)
