With

This function can be used to call multiple functions of an object without specifying a receiver. The function accepts an object and a receiver function of the same type as the object:

val stringBuilder = StringBuilder()
with(stringBuilder) {
appendln("First Line")
appendln("Second Line")
appendln("Third Line")
}

Because the lambda is a receiver function, inside the lambda we have access to the object that was passed as an argument. In this case, we call appendln and the object that receives this function call is the one we pass in as the first argument.

With this function we can also return a different value. In the previous example, we didn’t have a return value. Here’s a similar example, but here a string is used as the return type:

val str: String = with(StringBuilder()) {
appendln("First Line")
appendln("Second Line")
appendln("Third Line")
toString()
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.191.47