What is the difference between with and apply. From what I know the following code does the same thing:
swingElement.apply { minWidth = ENABLED_COLUMN_WIDTH maxWidth = ENABLED_COLUMN_WIDTH preferredWidth = ENABLED_COLUMN_WIDTH } with(swingElement) { minWidth = ENABLED_COLUMN_WIDTH maxWidth = ENABLED_COLUMN_WIDTH preferredWidth = ENABLED_COLUMN_WIDTH }
Is there any difference and should I use one over the other? Also, are there some cases where one would work and the other won't?
Kotlin apply vs with with runs without an object(receiver) whereas apply needs one. apply runs on the object reference, whereas with just passes it as an argument. The last expression of with function returns a result.
Calls the specified function block with the given receiver as its receiver and returns its result.
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.
In Kotlin, apply is an extension function on a particular type and sets its scope to object on which apply is invoked. Apply runs on the object reference into the expression and also returns the object reference on completion.
There're two differences:
apply
accepts an instance as the receiver while with
requires an instance to be passed as an argument. In both cases the instance will become this
within a block.
apply
returns the receiver and with
returns a result of the last expression within its block.
I'm not sure there can be some strict rules on which function to choose. Usually you use apply
when you need to do something with an object and return it. And when you need to perform some operations on an object and return some other object you can use either with
or run
. I prefer run
because it's more readable in my opinion but it's a matter of taste.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With