https://grokonez.com/kotlin/kotlin-return-function-function
Kotlin return Function from Function
With Kotlin, we can define a function that chooses the appropriate logic variants for specific cases and returns one of them as another function. In this tutorial, we're gonna look at how to return Function from Function.
I. Technology
- Java 1.8
- Kotlin 1.1.2
II. Overview
- To declare this kind of function, we specify a function type as its return type
-
To return a function, we write a
return
expression followed by a lambda, a method reference, or another expression of a function typefun funcName(input: InputType): (FuncInputType1, FuncInputType2) -> FuncReturnType { return [function type] }
III. Practice
1. Helper Class with function
package com.javasampleapproach.returnfunction
enum class Level { STANDARD, VIP }
class ChargeManagement {
companion object {
fun getChargeCalculator(level: Level): (Order) -> Double {
if (level == Level.VIP) {
return { order -> 3 + 0.8 * order.quantity }
}
return { order -> 1.2 * order.quantity }
}
}
}
Top comments (0)