Fabian Braun
08/03/2020, 10:15 AM.let
in particular)
Sometimes I have a hard time to decide about when to use .let
and when local variables should be preferred. Consider the example from https://kotlinlang.org/docs/reference/scope-functions.html#let which reads like:
val numbers = listOf("one", "two", "three", "four")
val modifiedFirstItem = numbers.first().let { firstItem ->
println("The first item of the list is '$firstItem'")
if (firstItem.length >= 5) firstItem else "!" + firstItem + "!"
}.toUpperCase()
println("First item after modifications: '$modifiedFirstItem'")
It could be rewritten to:
val numbers = listOf("one", "two", "three", "four")
numbers.first().let { firstItem ->
println("The first item of the list is '$firstItem'")
if (firstItem.length >= 5) firstItem else "!" + firstItem + "!"
}.toUpperCase().let { modifiedFirstItem ->
println("First item after modifications: '$modifiedFirstItem'")
}
However, in my opinion the second .let
makes the code less readable in this second snippet.
I have heard people say that local variables are not good kotlin-style and you should be using scope-functions but I couldn’t find any resources for that claim. Would be grateful for style-recommendations / resources on that.gildor
08/03/2020, 12:10 PMlocal variables are not good kotlin-styleDon't listen those people Use what is more readable for this particular case
gildor
08/03/2020, 12:13 PMTobias Berger
08/04/2020, 7:57 AM?.let
gildor
08/04/2020, 8:00 AMTobias Berger
08/04/2020, 8:09 AMgildor
08/04/2020, 8:10 AMandyg
08/06/2020, 4:05 PMnumbers.first().let {
Pair( it, (if (it.length >= 5) it else "!$it!").toUpperCase() )
}.also {
println("The first item of the list is '${it.first}'" + "\n" +
"First item after modifications: '${it.second}'")
}
andyg
08/06/2020, 4:07 PMgildor
08/06/2020, 4:19 PMgildor
08/06/2020, 4:24 PMval original = numbers.first()
val modified = if (original.length >= 5) {
original
} else {
"!$original!"
}.toUpperCase()
println("The first item of the list is '$number'" + "\n" +
"First item after modifications: '$modified'")
No additional allocations, easy to refactor (extract modified to own function, move println to own function)
Also you use it
, but as soon you start adding some nested constructions, it
becomes even more hard to understand, so you have to add namesandyg
08/07/2020, 2:48 AMPair
only goes so far, but Kotlin gives you data classes and the ability to define names inline (instead of it
and this
). But every developer should use what works best for them, Kotlin is great because there are so many options!Fabian Braun
08/07/2020, 9:27 AM