We can do
val obj = Obj()
with (obj) {
objMethod1()
objMethod2()
}
But is there a way to do this?
val obj = with(Obj()) {
objMethod1()
objMethod2()
}
To solve a common case where you create an object and call a few methods on it to initialise its state.
Sure, you can use the .apply { }
stdlib function, which
Calls the specified function block with
this
value as its receiver and returnsthis
value.
public inline fun <T> T.apply(block: T.() -> Unit): T { block(); return this }
Usage example:
val obj = Obj().apply {
objMethod1()
objMethod2()
}
You can find it among many other Kotlin idioms here in the reference.
Your second example works too - just make sure that the lambda returns the correct value (the result of the last expression is the returned value of the with
expression):
val obj = with(Obj()) {
objMethod1()
objMethod2()
this // return 'this' because we want to assign the new instance to obj
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With