I have noticed that some/many kotlin stdlib functi...
# android
l
I have noticed that some/many kotlin stdlib functions lack of escape, e.g.
repeat
. In the first place it's not clear what a
return@repeat
does. I would expect it leaves the iteration but instead it skips the iteration. AFAIK it's not possible to escape from
repeat
??!! And I guess the name does not implicitly tell that the repetition has to be finished. A
repeatUntil
counterpart would help here. Another example where a
return
is missleading:
map
,
mapValues
,
mapKeys
,
associateBy
,
associateWith
etc. Here I would expect that a
return
skips the current item, but instead the
return
gets part of data (
Unit
). Some
..NotNull
counterparts would help here. What do you guys think about that?
a
while
and
for
loops work great and support both
continue
and
break
🙂 saving 1-3 lines of code isn't a very big payoff for having to learn and remember dozens of edge case stdlib functions to read kotlin
l
That's true. Thanks for your input Adam
e
return
always returns from the nearest enclosing function, even if it's a non-local return (only possible inside inline lambdas), while
return@label
returns from a labeled lambda, where the label can be explicit
label@{ return@label }
or otherwise is implicitly labeled by the name of the function the lambda is being given to
there is nothing special about
repeat
or
map
or anything
you can "break" a repeat by returning to an outer scope,
Copy code
run {
    repeat(1) {
        return@run
    }
}
but why would you do that instead of a
for
loop that you can simply
break
from?
l
@ephemient My problem is that you can't escape from these functions, but yes you always have the possibility to go with simple loops. When working with Kotlin the first I do if I have to solve an algorithm is to look for a proper stdlib function. When I use simple loops it doesn't feel like Kotlin anymore, do you know what I mean? ^^ But there is one advantage of stdlib functions over custom code: the intention is more clear with stdlib functions. For repeat maybe it might not matter but if you work with
associateWith
and want to skip nullables, you can't do this without writing your own extension function or general kotlin code
e
you can build your own out of existing parts,
Copy code
inline fun <K, V: Any> Iterable<K>.associateWithNotNull(
    valueTransform: (K) -> V?
): Map<K, V> = mapNotNull {
    it to (valueTransform(it) ?: return@mapNotNull null)
}.toMap()
or
Copy code
buildMap {
    for (key in this@associateWithNotNull) {
        put(key, valueTransform(key) ?: continue)
    }
}
you could propose it to be added to stdlib but presumably they didn't anticipate enough usage to make this shortcut
l
Yeah, I already wrote my own extension function. Anyway thanks for your thoughts