Kotlin with-statement as expression

We can do it

val obj = Obj() with (obj) { objMethod1() objMethod2() } 

But is there a way to do this?

 val obj = with(Obj()) { objMethod1() objMethod2() } 

To solve the usual case when you create an object and call several methods to initialize its state.

+8
kotlin
source share
2 answers

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

Invokes the specified function block with this value as the receiver and returns the value of this .

 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 link .

+19
source share

Your second example also works - just make sure that the lambda returns the correct value (the result of the last expression is the return value of the with expression):

 val obj = with(Obj()) { objMethod1() objMethod2() this // return 'this' because we want to assign the new instance to obj } 
+4
source share

All Articles