Higher Order Functions in Kotlin

When we say a function is higher oder it at-least has one of these

  1. it should accept a function as an argument
  2. 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 :)

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade