Sunday 19 April 2020

Kotlin : "it" keyword (Post 14)

Hi ,

Let's discuss the "it" keyword, with lambda expression.

it keyword is basically is used as implicit the single parameter.

If any lambda expression is using one parameter , then it can be replaced with "it" keyword .

Here is a simple example for understanding : 
override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        getLength("Android", { a -> a.length })
        getLength("Android", { it.length })
    }
    /**
     * High Level Functions
     */
    fun getLength(a: String, myExp: (String) -> Int) {
        println(myExp(a))
    }

Here we can see that "a" argument is used to get the length of "a" lambda expression is used.
So it can be replaced as  "a -> a" to "it" , and it is only applicable for single parameter.

That's all for this post. Will share another post soon , till then Happy Coding :)


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...