# Why is "with(foo) { bar() }" preferred over "foo.bar()"?

**URL:** <https://discuss.kotlinlang.org/t/why-is-with-foo-bar-preferred-over-foo-bar/11512>\
**Category:** Language Design\
**Created:** [February 10, 2019, 2:14am UTC](https://discuss.kotlinlang.org/t/why-is-with-foo-bar-preferred-over-foo-bar/11512 "2019-02-10T02:14:38Z")\
**Posts on this page:** 15\
**Page:** 1

<div class="post-metadata">

**Author:** ![kuhrusty](https://avatars.discourse-cdn.com/v4/letter/k/898d66/32.png) [@kuhrusty](https://discuss.kotlinlang.org/u/kuhrusty)\
**Post date:** [February 10, 2019, 2:14am UTC](https://discuss.kotlinlang.org/t/why-is-with-foo-bar-preferred-over-foo-bar/11512/1 "2019-02-10T02:14:38Z")

</div>

Hey, I’ve racked up about 15 minutes of Kotlin experience, and am wondering about `with()`.

In [this Android developer page](https://developer.android.com/training/notify-user/build-notification#kotlin) (which is just what I happen to be using in experimenting with Kotlin), the “Show the notification” section about a third of the way down the page has this example:

```
with(NotificationManagerCompat.from(this)) {
    notify(notificationId, mBuilder.build())
}

```

First, that _is_ roughly equivalent to this, right? (They seem to do the same thing.)

```
NotificationManagerCompat.from(this).notify(notificationId, mBuilder.build())

```

If so, **is the first approach the generally preferred way to do it** in Kotlin (and if so, why), or is the author of that article a weirdo? (I acknowledge that those two statements are not mutually exclusive.)

Second–and unrelated, I guess, but you’re already here–I gather that these two are equivalent:

```
// block outside parentheses
with(foo) { bar() }

// block inside parentheses
with(foo, { bar() })

```

Looking at the signature for `with()`, the second is what I would expect to see, but the compiler gives a warning, saying the lambda should be moved outside the parentheses. _Why?!_ (I notice that, in the `List.fold()` example [here](https://kotlinlang.org/docs/reference/lambdas.html), the lambda is inside the parentheses; pasting that into the compiler gives the same warning.) If a method takes two arguments, putting one _inside_ the parentheses and one _outside_ rubs me the wrong way!

---

<div class="post-metadata">

**Author:** ![darksnake](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/darksnake/32/2479_2.png) [@darksnake](https://discuss.kotlinlang.org/u/darksnake)\
**Post date:** [February 10, 2019, 10:46am UTC](https://discuss.kotlinlang.org/t/why-is-with-foo-bar-preferred-over-foo-bar/11512/2 "2019-02-10T10:46:19Z")

</div>

> [@](#):
>
> Why is “with(foo) { bar() }” preferred over “foo.bar()

It is not. `with` is used for either calling multiple statements with one receiver, or to use member extensions inside the code block.

---

<div class="post-metadata">

**Author:** ![Wasabi375](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/wasabi375/32/4741_2.png) [@Wasabi375](https://discuss.kotlinlang.org/u/Wasabi375)\
**Post date:** [February 10, 2019, 10:51am UTC](https://discuss.kotlinlang.org/t/why-is-with-foo-bar-preferred-over-foo-bar/11512/3 "2019-02-10T10:51:24Z")

</div>

Let me answer the easy part first

> [@kuhrusty](#):
>
> Looking at the signature for `with()` , the second is what I would expect to see, but the compiler gives a warning, saying the lambda should be moved outside the parentheses. _Why?!_ (I notice that, in the `List.fold()` example [here](https://kotlinlang.org/docs/reference/lambdas.html), the lambda is inside the parentheses; pasting that into the compiler gives the same warning.) If a method takes two arguments, putting one _inside_ the parentheses and one _outside_ rubs me the wrong way!

In kotlin you can omit the parentheses around the last argument of a function if it’s a lambda.

```kotlin
with(foo) { bar() }

```

is the same as

```kotlin
with(foo, { bar() })

```

This is used to make code more readable. Especially for scoping functions like `with`, `run`, `let`, `also` and `apply` this is the preferred way of writing lambdas.

> If a call takes a single lambda, it should be passed outside of parentheses whenever possible.

[https://kotlinlang.org/docs/reference/coding-conventions.html#lambda-formatting](https://kotlinlang.org/docs/reference/coding-conventions.html#lambda-formatting)  
So I guess the example you found is not following the coding convention as stated. I guess the reason is that they only explain this rule further down the page.

* * *

> [@kuhrusty](#):
>
> First, that _is_ roughly equivalent to this, right? (They seem to do the same thing.)

Yes, it’s exactly the same. `with` is one of the [scoping functions](https://kotlinlang.org/docs/reference/coding-conventions.html#using-scope-functions-applywithrunalsolet) in kotlin.  
In general they are used to make code more readable. `with` allows you to call multiple functions or access multiple properties on the same object without having to use it’s name over and over again. It changes the scope from your current to the scope of the object you pass to with. Also this does not change the generated bytecode at all. All it does is give you a more descriptive way of writing code.

---

<div class="post-metadata">

**Author:** ![SOF3](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/sof3/32/5646_2.png) [@SOF3](https://discuss.kotlinlang.org/u/SOF3)\
**Post date:** [February 10, 2019, 3:45pm UTC](https://discuss.kotlinlang.org/t/why-is-with-foo-bar-preferred-over-foo-bar/11512/4 "2019-02-10T15:45:31Z")

</div>

Let me elaborate a bit more on why it is “a more descriptive way of writing code”:  
Sometimes you have two or three verbose lines of code that operate on the same thing, and the scope of them is very local to those several lines. For example:

```auto
fun abc(): Int
fun xyz(): Double{
  val base = 1.0
  val tmp = abc()
  val ratio = if(tmp == 0.0) -1 else (1.0 / tmp)
  return base + ratio
}

```

Alternatively, the value of `ratio` could be written as `if(abc() == 0.0) -1 else (1.0 / abc())`. But wait… this alternative calls the `abc()` function twice, which might cause undesired performance or semantic effects. But to cache the return value of `abc()` into `tmp`? This leads to an extra line of code, and we have to invent a meaningful name for the result of `abc()`, and using `tmp` leads to problems if we reuse the same technique later on: duplicate variable declaration (similar to “Duplicate variable `i`” with multiple `for(var i = 0; ...)` loops in JavaScript).

So in Kotlin, we could organize this logic into a single statement:

```auto
fun xyz(): Double{
  val base = 1.0
  val ratio = with(abc()) { if(this == 0.0) -1 else (1.0 / this) }
  return base + ratio
}

```

There are other idiomatic ways to do this in Kotlin:

```auto
// if you want an object-oriented style
val ratio = abc().run { if(this == 0.0) -1 else (1.0 / this) }

// in my opinion "it" is more intuitive than "this" and prevents context overriding issues
val ratio = abc().let { if(it == 0.0) -1 else (1.0 / it) }

// this involves nullable Double, not sure if kotlin compiler can optimize away Double object boxing
val ratio = abc().takeUnless { it == 0.0 } ?: -1
// or equivalently:
val ratio = abc().takeIf {it != 0.0 } ?: -1

```

So to conclude: I would use `with`/`run`/`let` if there is a temp variable that I don’t want to think of a name for and will not be used for more than 3 lines

---

<div class="post-metadata">

**Author:** ![Wasabi375](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/wasabi375/32/4741_2.png) [@Wasabi375](https://discuss.kotlinlang.org/u/Wasabi375)\
**Post date:** [February 10, 2019, 6:53pm UTC](https://discuss.kotlinlang.org/t/why-is-with-foo-bar-preferred-over-foo-bar/11512/5 "2019-02-10T18:53:17Z")

</div>

I mostly agree, but I don’t think `with`/`run`/`let` are equally valid here. Of cause they all achieve the same thing, but still. You already point out that “it” is more intuitive than “this” but it goes further.

IMO all of those scoping functions have a different meaning. `run` implies that I want to run some action on the object, `with` means that I want to switch the context of my execution to the object.  
`let` on the other hand means, I just want to take this value as a temporary value and do some more calculations on it. Therefor `let` is the right choice in this situation. (This is my take on those functions, I don’t think this is stated in any coding convention for kotlin)

* * *

I’m also not sure about the boxing optimization, but it won’t work anyways as you no longer invert the value. You would need to write

```kotlin
val ratio = 1 / abc().takeIf { it != 0.0 } ?: -1

```

---

<div class="post-metadata">

**Author:** ![kuhrusty](https://avatars.discourse-cdn.com/v4/letter/k/898d66/32.png) [@kuhrusty](https://discuss.kotlinlang.org/u/kuhrusty)\
**Post date:** [February 10, 2019, 9:02pm UTC](https://discuss.kotlinlang.org/t/why-is-with-foo-bar-preferred-over-foo-bar/11512/7 "2019-02-10T21:02:11Z")

</div>

I’m not sure I agree with you guys about the readability. Suppose we have `fun abc(): Foo`, and this code:

```
val unsightlyTempName = abc()
unsightlyTempName.foo()
bar()
unsightlyTempName.baz()

```

That may not be _pretty,_ but it’s absolutely _clear;_ there’s no question about what’s happening there. Now we replace it with `with()`:

```
with(abc()) {
    foo()
    bar()
    baz()
}

```

So clean! _But,_ what is that `bar()` there? The answer depends on whether the `Foo` class has a `bar()` method… and, worse, when that answer _changes_ in six months, this code silently breaks. Doesn’t that risk make `with()` basically poisonous?

(I mean, that _is_ a real problem, isn’t it? Isn’t it the case that adding a new method to an existing class risks silently breaking every place where objects of that class are used in `with()`?)

---

<div class="post-metadata">

**Author:** ![arocnies](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/arocnies/32/5143_2.png) [@arocnies](https://discuss.kotlinlang.org/u/arocnies)\
**Post date:** [February 10, 2019, 11:44pm UTC](https://discuss.kotlinlang.org/t/why-is-with-foo-bar-preferred-over-foo-bar/11512/8 "2019-02-10T23:44:05Z")

</div>

> [@kuhrusty](#):
>
> (I mean, that _is_ a real problem, isn’t it? Isn’t it the case that adding a new method to an existing class risks silently breaking every place where objects of that class are used in `with()` ?)

It’s no more risk than a subclass’s risk that a superclass will change the subclass’s context by adding a new method.

I would not use `with` for simply fixing a bad variable name for two reasons.:

1. There are other, simpler options that don’t have any context switching risks
2. `with`, as Wasabi points out, is for switching contexts

As darksnake mentioned, I often find myself using `with` to switch contexts that include **extension functions** :

```run-kotlin
// In practice, I usually use this as an interface that would be implemented elsewhere. 
// That way I can use extension functions polymorphically.
class SpecialExtensions {
  fun String.hello() = println("Hello $this!")
  fun Int.foo() = this * 42
  fun Double.buzz() = "Buzz of $this"
}

fun main() {
  with(SpecialExtensions()) {
    "Bob".hello()
    println(11.foo())
    println(2.2.buzz())
  }
}

```

> [@Wasabi375](#):
>
> all of those scoping functions have a different meaning

^ As a side note, this is also true for function prefixes like `get`, `find`, `load`/`fetch`–they all communicate different meanings to the programmer.

---

<div class="post-metadata">

**Author:** ![kuhrusty](https://avatars.discourse-cdn.com/v4/letter/k/898d66/32.png) [@kuhrusty](https://discuss.kotlinlang.org/u/kuhrusty)\
**Post date:** [February 11, 2019, 2:39am UTC](https://discuss.kotlinlang.org/t/why-is-with-foo-bar-preferred-over-foo-bar/11512/9 "2019-02-11T02:39:23Z")

</div>

> [@arocnies](#):
>
> It’s no more risk than a subclass’s risk that a superclass will change the subclass’s context by adding a new method.

Can you give me an example of what you’re talking about? The closest I’m coming up with is if `Subclass` has a `foo()` method which does one thing, and then `Superclass` later adds a `foo()` method with different semantics… but A) that doesn’t exactly break existing calls to `Subclass.foo()`–they’re still doing exactly what you wanted them to do when you wrote them six months ago–and B) that _can’t_ happen in Kotlin, right? because the compiler will complain about `Subclass.foo()` not having `override`?

> [@arocnies](#):
>
> As darksnake mentioned, I often find myself using `with` to switch contexts that include **extension functions** :

Ah, I saw that, but had not read about extension functions yet. Thank you for the example.

---

<div class="post-metadata">

**Author:** ![darksnake](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/darksnake/32/2479_2.png) [@darksnake](https://discuss.kotlinlang.org/u/darksnake)\
**Post date:** [February 11, 2019, 5:17am UTC](https://discuss.kotlinlang.org/t/why-is-with-foo-bar-preferred-over-foo-bar/11512/10 "2019-02-11T05:17:32Z")

</div>

You guys are digging too deep for the question asked.  
Of course, if you want to do the things the hard way, then `with` is very important thing in kotlin it allows to define behaviors not in class, but in a lexical scope. In that case the class passed to `with` is used only for behavior container or even scope marker. If some variant of [KEEP-176](https://github.com/Kotlin/KEEP/pull/176) will be approved, then it will bring the whole new style of programming (defining behaviors not for receiver, but for other objects in receiver scope).  
I’ve recently written an [article](https://proandroiddev.com/an-introduction-context-oriented-programming-in-kotlin-2e79d316b0a2) about it.

---

<div class="post-metadata">

**Author:** ![dalewking](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/dalewking/32/1496_2.png) [@dalewking](https://discuss.kotlinlang.org/u/dalewking)\
**Post date:** [February 15, 2019, 7:02pm UTC](https://discuss.kotlinlang.org/t/why-is-with-foo-bar-preferred-over-foo-bar/11512/11 "2019-02-15T19:02:21Z")

</div>

To add to the excellent answers already given, I find that I rarely ever use `with`, preferring `run`, `let`, `apply` and `also`.

I think it exists for somewhat historical reasons, because early on `apply` and `also` did not exist. Once `apply` and later `also` were added the need for `with` was almost non-existent. It might have some good use cases but I wouldn’t focus on it.

---

<div class="post-metadata">

**Author:** ![darksnake](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/darksnake/32/2479_2.png) [@darksnake](https://discuss.kotlinlang.org/u/darksnake)\
**Post date:** [February 16, 2019, 5:57am UTC](https://discuss.kotlinlang.org/t/why-is-with-foo-bar-preferred-over-foo-bar/11512/12 "2019-02-16T05:57:13Z")

</div>

Currently `something.run{}` is equivalent to `with(something){}`.

If KEEP-176 would pass, than `with` will have additional meaning, since it will be able to take multiple arguments.

---

<div class="post-metadata">

**Author:** ![dalewking](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/dalewking/32/1496_2.png) [@dalewking](https://discuss.kotlinlang.org/u/dalewking)\
**Post date:** [February 16, 2019, 4:37pm UTC](https://discuss.kotlinlang.org/t/why-is-with-foo-bar-preferred-over-foo-bar/11512/13 "2019-02-16T16:37:20Z")

</div>

> [@darksnake](#):
>
> Currently `something.run{}` is equivalent to `with(something){}` .

Hmm. I had thought with was like apply. Maybe I should use it more since I kind of like the with version.

But then again I don’t really do much Kotlin programming since I am strictly Java at my day job and side projects in flutter/dart.

---

<div class="post-metadata">

**Author:** ![darksnake](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/darksnake/32/2479_2.png) [@darksnake](https://discuss.kotlinlang.org/u/darksnake)\
**Post date:** [February 16, 2019, 6:12pm UTC](https://discuss.kotlinlang.org/t/why-is-with-foo-bar-preferred-over-foo-bar/11512/14 "2019-02-16T18:12:17Z")

</div>

Yeah, you are right. `apply` equals `with`. `run` returns a result.

---

<div class="post-metadata">

**Author:** ![dalewking](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/dalewking/32/1496_2.png) [@dalewking](https://discuss.kotlinlang.org/u/dalewking)\
**Post date:** [February 16, 2019, 7:40pm UTC](https://discuss.kotlinlang.org/t/why-is-with-foo-bar-preferred-over-foo-bar/11512/15 "2019-02-16T19:40:57Z")

</div>

No, you were correct, with is like run in that

```
with(foo) { ... }

```

is the same as

```
 foo.run { ... }

```

But I remembered that the reason run gets preferred is that you often want to chain it to previous expressions. It is nothing for me to have a sequences of runs and lets.

---

<div class="post-metadata">

**Author:** ![mice777](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/mice777/32/4560_2.png) [@mice777](https://discuss.kotlinlang.org/u/mice777)\
**Post date:** [February 22, 2019, 7:23pm UTC](https://discuss.kotlinlang.org/t/why-is-with-foo-bar-preferred-over-foo-bar/11512/16 "2019-02-22T19:23:42Z")

</div>

> [@dalewking](#):
>
> To add to the excellent answers already given, I find that I rarely ever use `with` , preferring `run` , `let` , `apply` and `also` .

I agree fully. I rarely use `with(){}` because to me it seems same like `.run{}` just with swapped name/parameter, so if `with()` wasn’t there, I wouldn’t care at all.
