Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin with-statement as an expression

Tags:

kotlin

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.

like image 919
Yuri Geinish Avatar asked Oct 21 '16 17:10

Yuri Geinish


2 Answers

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.

like image 182
hotkey Avatar answered Oct 10 '22 14:10

hotkey


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
}
like image 24
Andreas Dolk Avatar answered Oct 10 '22 12:10

Andreas Dolk