Tuesday 21 April 2020

Kotlin : "with" & "apply" keywords (Post 15)

Hi  ,

Again I am sharing two basic and import keywords that are : "with" & "apply" .Both keywords are part of Kotlin Standard Library

Let's take a look :

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

        //with keyword
        with(Mobile()){
            os = "Android"
            version = "10.0.0"
        }

        // apply keyword
        Mobile().apply{
            os = "Android"
            version = "10.0.0"
        }.checkStatus()
    }

    /**
     * Mobile class
     */
    class Mobile {
        var os: String = ""
        var version: String = ""

        fun checkStatus() {
            println("I am in Mobile class!")
        }
    }


Here we can see that we can assign the value to the variables of mobile class using with and apply keyword .

With the help of apply keyword we can also call the member function of that class.

That's all for this post , I will again share some new concept of Kotlin Language  , 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...