Kotlin with

Kotlin with is a function which accepts a receiver object and has a block of code. In this block of code, receiver’s properties and methods can be accessed without actually referring to the object.

Kotlin with can make the code concise and look readable.

Example

In the following example, we will pass a String value for receiver object to with() and access the properties and functions of the String in the block.

Main.kt

fun main(args: Array<String>) {
    val str = "Hello World!"
    with (str) {
        println(length)
        println(uppercase())
    }
}

Output

12
HELLO WORLD!

Inside the with-block, we have accessed length property and called uppercase() function of the receiver object str, with actually referencing the object str again like str.length or str.uppercase().

Access Receiver Itself in With-Block

To access receiver itself in the with-block, use this keyword.

Main.kt

fun main(args: Array<String>) {
    val str = "Hello World!"
    with (str) {
        print(this)
    }
}

Output

Hello World!

Return Value from With-Block

We can return a value from with-block. Just place the return value as the last statement in the with-block.

In the following example, we will return lowercase value of the String from with-block.

Main.kt

fun main(args: Array<String>) {
    val str = "Hello World!"
    val result = with (str) {
        //some code
        lowercase()
    }
    println(result)
}

Output

hello world!

Now, let us return length of the receiver object str from the with-block.

Main.kt

fun main(args: Array<String>) {
    val str = "Hello World!"
    val result = with (str) {
        //some code
        length
    }
    println("Returned Value: " + result)
}

Output

Returned Value: 12

Conclusion

In this Kotlin Tutorial, we learned what a Kotlin with function is, and how to use this to create a scope (with-block) for an object (receiver) and access its members and functions.