dave08
03/28/2024, 10:19 AMvar
when multiple functions return enriched data on the same structure:
var result = getFoo()
result = enrich1(result)
result = enrich2(result)
...
?Sam
03/28/2024, 10:22 AMval result = getFoo()
.let(::enrich1)
.let(::enrich2)
Or even `fold`:
val result = listOf(::enrich1, ::enrich2)
.fold(getBar()) { intermediate, enrich ->
enrich(intermediate)
}
dave08
03/28/2024, 10:25 AMvar
?Johann Pardanaud
03/28/2024, 10:27 AMvar
, it's not that terrible, however let
is a good option I think, you can even use it with more params and keep your code quite clean:
val result = getFoo()
.let { enrich1(it, param2) }
.let(::enrich2)
Sam
03/28/2024, 10:27 AMlet { enrich1(it, otherStuff) }
if needs be. But I don't have anything against a good old-fashioned var
if it helps to make the intent clear.Sam
03/28/2024, 10:27 AMdave08
03/28/2024, 10:28 AMlet { }
makes that clearer. Thanks!dave08
03/28/2024, 10:29 AMdave08
03/28/2024, 11:00 AMval result = getFoo().let { it + enrich(...) }....
dave08
03/28/2024, 11:01 AM+=
...Johann Pardanaud
03/28/2024, 11:06 AMvar
, it's okay 🙂
or you could also do the following to obtain a val
at the end:
val result = run {
var builder = "hello"
builder += " world"
builder
}
assert(result == "hello world")
Alejandro Serrano.Mena
03/28/2024, 12:59 PMresult
, they should directly mutate it instead of returning a copy that you're then "smashing"
var foo = getFoo().apply {
enrich1(it)
enrich2(it)
}
dave08
03/28/2024, 1:24 PMAlejandro Serrano.Mena
03/28/2024, 1:28 PMvar
inside a function because it makes the code cleaner/more efficient, that's perfectly fine, as you are not contaminating other.
Having said so, for big data structures which are refined by steps having variables is a common pattern. For example, inside the Kotlin compiler this is how it works: the parsed program is a big tree, and different phases (e.g., type inference) change some data (in the example of type inference, it changes null
in the type to the inferred one). This avoids the need to copy several times, and (in that specific case) would also allow to transform separate parts of the tree concurrentlydave08
03/28/2024, 4:04 PM