The documentation says:
inline fun <T, R> with(receiver: T, block: T.() -> R): R (source)
Calls the specified function block with the given receiver as its receiver and returns its result.
The way I think of it is that it is calling a function (the block
) where this
in the scope of the block
is the receiver
.
Whatever the block
returns is the return type.
Essentially calling a method where you provide the implicit this
and can return any result from it.
Here is an example to demonstrate:
val rec = "hello"
val returnedValue: Int = with(rec) {
println("$this is ${length}")
lastIndexOf("l")
}
The rec
in this case is the receiver of the function call - the this
in the scope of the block
. The $length
and lastIndexOf
are both called on the receiver.
The return value can be seen to be an Int
because that is the last method call in the body
- that is the generic type parameter R
of the signature.