Sunday 19 April 2020

Kotlin : Lambda Expressions (Post 13)

Hi ,

Continuing  , the series of Kotlin , here I am again discussing few things about Lambda Expressions.

The main aim of writing the Lambda Expressions is to simplify the  code and reduce the number of lines  , with easily understandable .

I am here sharing a simple example of Lambda Expression , and passing it in the argument of one functions . The  functions which are having lambda expressions as an argument , are called High Order Functions.


override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        /** Lambda Expressions
        variable name : Signature = {Parameters -> method body}
        */
        var myLambdaFunction: (Int, Int) -> Unit = { a, b -> println(a + b) }
        getSum(4, 5, myLambdaFunction)
    }

    /**
     * High Level Functions
     */
    fun getSum(a: Int, b: Int, myLambdaFunction: (Int, Int) -> Unit) {
        myLambdaFunction(a, b)
    }


Also we can call the above method like this as well :

   getSum(4, 5, myLambdaFunction)

   getSum(4, 5, { a, b -> println(a + b)})

   getSum(4, 5) { a, b -> println(a + b)}

This is very basic expression of Lambdas . For getting more uses of Lambdas we can check out here :

https://kotlinlang.org/docs/reference/lambdas.html


No comments:

Post a Comment

Advanced Kotlin Coroutines : Introduction

 Hi,  Today I am unwraping the topic in Kotin world i.e. Coroutine . If you want to get started with Kotlin coroutine and ease your daily de...