DEV Community

loizenai
loizenai

Posted on

Kotlin return Function from Function

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 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 }
    }
}
Enter fullscreen mode Exit fullscreen mode

}

https://grokonez.com/kotlin/kotlin-return-function-function

Top comments (0)