Author profile picture

Higher-Order Function

A higher-order function is a function does at least one of these:

  1. It accepts a function as an argument
  2. It returns a function as a result

Kotlin supports higher-order functions. In the following example, calculateCost() accepts a function as an argument, and getDiscount() returns a function as a result.

Example

class Product(val name: String, val price: Double)

val shippingCost = 4.0
val taxRate = 0.08

fun main(args: Array<String>) {
    val product = Product("Widget", 10.0)

    println(calculateCost(product, getDiscount("10%_OFF")))
    println(calculateCost(product, getDiscount("5_BUCKS_OFF")))
}

fun calculateCost(product: Product, discount: (Double) -> Double): Double {
    val subtotal = discount(product.price) + shippingCost
    val tax = subtotal * taxRate
    return subtotal + tax
}

fun getDiscount(discountCode: String): (Double) -> Double = when (discountCode) {
    "10%_OFF" -> { p -> p * 0.9 }
    "5_BUCKS_OFF" -> { p -> Math.max(p - 5.0, 0.0) }
    else -> { p -> p }
}

Share this article:

  • Share on Twitter
  • Share on Facebook
  • Share on Reddit