Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: Apply vs With

Tags:

kotlin

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?

like image 714
n9Mtq4 Avatar asked Apr 14 '16 13:04

n9Mtq4


People also ask

What is difference between with and apply in Kotlin?

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.

What is with () in Kotlin?

Calls the specified function block with the given receiver as its receiver and returns its result.

Why apply is used in Kotlin?

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.

What does apply mean Kotlin?

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.


1 Answers

There're two differences:

  1. 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.

  2. 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.

like image 200
Michael Avatar answered Sep 29 '22 00:09

Michael