https://kotlinlang.org logo
#codereview
Title
# codereview
j

Jonathan Ellis

08/09/2022, 3:12 PM
is there a more idiomatic way to write a map-with-loop like this?
Copy code
val flowed = allShapes.map {
            var p = it
            for (i in 0 until STRETCH_ITERATIONS) {
                p = flow(p)
            }
            p
        }
e

ephemient

08/09/2022, 3:20 PM
Copy code
allShapes.map {
    (0 until STRETCH_ITERATIONS).fold(it) { p, _ ->
        fold(p)
    }
}
j

Jonathan Ellis

08/09/2022, 3:21 PM
TIL about fold, thanks!
j

Joffrey

08/09/2022, 5:27 PM
Also, when a for loop is about repeating something some number of times, it's better expressed with the
repeat(n) { ... }
function. So in a case where
fold
wouldn't be a solution to your problem, you could at least replace the loop:
Copy code
val flowed = allShapes.map {
    var p = it
    repeat(STRETCH_ITERATIONS) {
        p = flow(p)
    }
    p
}
e

ephemient

08/09/2022, 5:40 PM
"better" is arguable; you can't break early out of
repeat
, and the
rangeTo
in a
for
loop is intrinsified so it doesn't cost anything more than
repeat
j

Joffrey

08/09/2022, 5:43 PM
Of course if you need complex control flow like
break
and
continue
, it's not possible. But such cases would probably not be better expressed by
repeat
anyway - it's not about repeating something N times if you break early.
j

Jonathan Ellis

08/09/2022, 5:44 PM
it's pretty common to write "loop until condition or a maximum of N times"
j

Joffrey

08/09/2022, 5:47 PM
Yes, but it's not the case here. My point is, if what you need is a plain "repeat N times" (like here),
repeat
is very clear and meant for this. But of course
repeat
is for repeating, not for other stuff. That said, I have not needed a for loop in Kotlin for quite some time, there usually are clearer alternatives for most use cases.
3 Views