When you have an object already initialized, what is the best kotlin scope function to use for setting multiple properties to this object (I don't need to return the instance of the object but only setting properties)
myObject.run {
text = "",
id = 0,
color = "#111111"
}
or
with(myObject) {
text = "",
id = 0,
color = "#111111"
}
or
myObject.apply {
text = "",
id = 0,
color = "#111111"
}
or maybe "let" ? I'm little confused because all scope functions can be used to achieve that but which is the must appropriated ?
CodePudding user response:
I don't need to return the instance of the object but only setting properties
All scope functions return something. Some return the context object (apply/also) while others return lambda result (let/with/run). If you don't need the return value you can ignore them.
Here you want to mutate the properties of myObject
, so apply
would make the most sense. It provides the context object as this
inside lambda and returns the object itself after executing the lambda.
Using with
or run
will return Unit
(which is the result of lambda). Since you don't care about the result, you go with any of these but as I said earlier, apply
makes the most sense here.
Quoting the docs,
Use
apply
for code blocks that don't return a value and mainly operate on the members of the receiver object. The common case for apply is the object configuration. Such calls can be read as “ apply the following assignments to the object.”
run
is useful when your lambda contains both the object initialization and the computation of the return value.
We recommend
with
for calling functions on the context object without providing the lambda result. In the code, with can be read as “ with this object, do the following.”
Btw, if myObject
is a data class, I would suggest using the copy
function for creating a new instance by modifying some properties of myObject
.
val newObject = myObject.copy(text = "", id = 0, color = "#111111")