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.
>>> Refer to: JavaSampleApproach.com
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 type
1 2 3 4 |
fun funcName(input: InputType): (FuncInputType1, FuncInputType2) -> FuncReturnType { return [function type] } |
III. Practice
1. Helper Class with function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
package com.kotlination.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 } } } } |
getChargeCalculatorreturns()
returns a function that takes an Order
and returns a Double
.
2. Class for FuncInputType
1 2 3 4 |
package com.kotlination.returnfunction class Order(val quantity: Int) { } |
3. Run and check Result
Run the code below:
1 2 3 4 5 6 7 8 9 10 11 12 |
package com.kotlination.returnfunction fun main(args: Array<String>) { val order = Order(10) val calculator1 = ChargeManagement.getChargeCalculator(Level.STANDARD) println("Charge for Standard Member: ${calculator1(order)}") val calculator2 = ChargeManagement.getChargeCalculator(Level.VIP) println("Charge for VIP Member: ${calculator2(order)}") } |
calculator1
and calculator2
are functions returned from getChargeCalculator()
function.
Check Result:
1 2 |
Charge for Standard Member: 12.0 Charge for VIP Member: 11.0 |