Foggy day

Kotlin - lambda expression -2 : function composition 본문

Kotlin

Kotlin - lambda expression -2 : function composition

jinhan38 2021. 3. 20. 19:04

 

 

class KotlinPlayGroundActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_kotlin_play_ground)

        val result = compose(::divide, ::multiply)
        println("result : ${result(3)}")

        val result2 = compose2(::divide, ::multiply)
        println("result2 : ${result2(4)}")

        val result3 = compose3(::divide, ::multiply)
        println("result3 : ${result3(5)}")

    }

    fun compose(f: (Int) -> Int, g: (Int) -> Int): (Int) -> Int = { value -> f(g(value)) }

    fun divide(n: Int) = n / 2

    fun multiply(n: Int) = n * n

    fun <U> compose2(f: (U) -> U, g: (U) -> U): (U) -> U = { f(g(it)) }

    fun <T, U, V> compose3(f: (U) -> V, g: (T) -> U): (T) -> V = {f(g(it))}
}