Daniel Pitts
09/17/2024, 8:31 PMx.run { doY() }
vs with(x) { doY() }
vs x.apply { doY() }
when the result doesn't matter? Does your opinion change if it's a multiline lambda?Daniel Pitts
09/17/2024, 8:33 PMapply
has different behavior than the other two if the overall expression result is returned, but in this case it is expected that the expression result is ignored entirely.Daniel Pitts
09/17/2024, 8:35 PMx.let { with(it) { doY() } }
Daniel Pitts
09/17/2024, 8:37 PMx
is instead an expression itself? For example, MyBuilderImpl().run
vs with(MyBuilderImpl())
Daniel Pitts
09/17/2024, 8:40 PMapply
looks good for single line lambdas on simple references.
2. with
looks good for the MyBuilderImpl()
example
3. run
looks good for multiline lambdas.
This is, of course, somewhat subjective, so hoping others can give better reasoning, or tell me why the agree with me 😉ephemient
09/17/2024, 8:47 PMx.run
, unless it's something like x?.run
. with(x)
reads the best to me, and x.apply
has its uses when returning x
.Klitos Kyriacou
09/18/2024, 8:21 AMx
is a long expression like a + b() + c.foo(d)
, then by using with(a + b() + c.foo(d)) { ... }
you start the sentence with with
, showing that you're about to do something with the expression. With ``(a + b() + c.foo(d)).run { ... }` all you see at first is a long expression and you don't know what you're about to do with it until you see run
. It looks more natural to English speakers to use with
because in English we usually put the object later on in a sentence. This may be different in some other languages where the object comes first.phldavies
09/18/2024, 9:10 AM.apply {}
makes sense as you're "applying" a change to receiver. For something that's a side-effect, I'd rather use x.also { it.doY() }
as it's clear that you're "also" doing something.phldavies
09/18/2024, 9:11 AMx
to the receiver, then x.also { with(it) { doY() } }
would read nicely although with extra nesting. but again, that makes more sense when part of a chain - which if you have x as a variable it's probably cleaner to just use with(x) { doY() }
Daniel Pitts
09/18/2024, 1:51 PMDaniel Pitts
09/18/2024, 1:53 PMrun
is just as a way to create a smaller scope for a val/var. This is rare though, as often times its better to just extract a new method in the first place.Daniel Pitts
09/18/2024, 1:55 PMDaniel Pitts
09/18/2024, 1:55 PMephemient
09/18/2024, 1:57 PMrun
without a receiver reads fine imo but it's usually unnecessary. smaller local scope doesn't really matter in Kotlin, unless you're running into shadowing (in which case maybe choose better names instead)ephemient
09/18/2024, 1:59 PMDaniel Pitts
09/18/2024, 2:03 PMDaniel Pitts
09/18/2024, 2:04 PM