The with() operator in Kotlin

There are times when there’s multiple lines of operations on the same object, and we do it by calling myObject instance everytime we do any operation. This makes our code repetitive and makes it look bad and ugly.

For example, when we put different values in the Intent, we do it like this:

    var intent = Intent()
    intent.putExtra("myInt", 0)
    intent.putExtra("myBool", false)
    intent.putExtra("myString", "hello string")
    startActivity(intent)

And when we receive this Intent in any other Activity, then we get all the values like this:

    var intent = getMyIntent()
    var myInt = intent.getInt("myInt", 0)
    var myBool = intent.getBoolean("myBool", false)
    var myString = intent.getString("myString")

Again, same ugly repetitive code block. Kotlin provides a better solution to this problem by using with operator. We can write above codes like this now:

    var intent = Intent()
    with(intent)
    {
        putExtra("myInt", 0)
        putExtra("myBool", false)
        putExtra("myString", "hello string")
    }
    startActivity(intent)

See! How clean this is. Similarly, we can use it at receiving Intent as well:

    var intent = getMyIntent()
    with(intent)
    {
        var myInt = getInt("myInt", 0)
        var myBool = getBoolean("myBool", false)
        var myString = getString("myString")
    }


If you liked this article, you can read my new articles below:


Wajahat Karim is Pakistan’s first Google Developer Expert in Android. As an experience Android developer, he deeply cares about it and keeps writing and speaking about it. He has written two worldwide 300+ pages books on Android development with more than 100 articles around the internet either on his website or his Medium publications. He is also a passionate contributor in open source and has created many Android libraries used by thousands of developers in their apps worldwide. As active public speaker, he spends lots of time giving talks in conferences and motivating people on Android development. You can find Wajahat most active on Twitter @WajahatKarim where he regularly shares all the good stuff about Android and community building.

Author's picture

Wajahat Karim

🔥 Google Dev Expert (GDE) in Android .
📱 Android Dev. 💻 Open Source Contributor . 📝 Technical Writer . 🎤 Public Speaker

Senior Android Developer

Karachi, Pakistan