Yuri Geinish
Yuri Geinish

Reputation: 17214

Kotlin with-statement as an expression

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.

Upvotes: 18

Views: 12043

Answers (2)

Andreas Dolk
Andreas Dolk

Reputation: 114767

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
}

Upvotes: 7

hotkey
hotkey

Reputation: 147941

Sure, you can use the .apply { } stdlib function, which

Calls the specified function block with this value as its receiver and returns this 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.

Upvotes: 31

Related Questions