https://kotlinlang.org logo
Title
u

Ubi

03/21/2019, 9:51 AM
Is it possible to have an inline block of code that returns an object. In the example below you have to “manually” call
invoke()
. Is there any other way to achieve this?
d

diesieben07

03/21/2019, 9:52 AM
Usually you can use
run
for this:
val users = listOf(
    run {
        val user = User()
        user.id = 1
        user
    }
)
👍 1
But in this case you can even simpler use `also`:
val users = listOf(
  User().also { it.id = 1 }
)
:kotlin: 1
w

wbertan

03/21/2019, 9:52 AM
Can use
apply
to "initialise"
val users = listOf(
                User().apply { id = 1 }
        )
:kotlin: 1
u

Ubi

03/21/2019, 9:57 AM
Thank 🙂