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 type

fun 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 }
		}
	}
}

getChargeCalculatorreturns() returns a function that takes an Order and returns a Double.

2. Class for FuncInputType


package com.javasampleapproach.returnfunction

class Order(val quantity: Int) {
}

3. Run and check Result

Run the code below:


package com.javasampleapproach.returnfunction

fun main(args: Array) {

	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:


Charge for Standard Member: 12.0
Charge for VIP Member: 11.0


By grokonez | August 30, 2017.

Last updated on April 14, 2021.



Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*