https://kotlinlang.org logo
#getting-started
Title
# getting-started
d

Dan O'Brien

02/15/2022, 8:30 PM
I have a class that does not take any parameters when instantiating, but it has a number of properties I need to set after. Is there any clean way to use a lambda or similar to set all of the properties inside one
{}
block after instantiating the class?
j

Joffrey

02/15/2022, 8:30 PM
You can use
apply
for this:
Copy code
val x = YourClass().apply {
    prop1 = 42
    prop2 = "test"
}
d

Dan O'Brien

02/15/2022, 8:32 PM
thank you!! That will be so much cleaner
j

Joffrey

02/15/2022, 8:35 PM
You can look up "scope functions" for this kind of little methods such as
let
,
also
,
apply
,
run
and
with
. They are all variations of the same thing, you have access to the instance as
this
or as parameter, and it either returns the initial object or the result of the lambda.
2 Views