https://kotlinlang.org logo
#stdlib
Title
# stdlib
n

nkiesel

12/28/2022, 12:50 AM
Any issues with adding a
chunked
(or
chunkedBy
) which takes a predicate instead of an Int? Something like
Copy code
fun <T> List<T>.chunkedBy(predicate: (T) -> Boolean): List<List<T>> =
    fold(mutableListOf(mutableListOf<T>())) { acc, item ->
        if (predicate(item)) {
            acc.add(mutableListOf())
        } else {
            acc.last().add(item)
        }
        acc
    }
m

marcinmoskala

12/28/2022, 7:21 AM
Are there any use-cases for that? It seems redundant and limiting to me.
n

nkiesel

12/28/2022, 10:36 PM
I regularly use it when converting a list of items into a grouped list. Example: List<String>, with groups separated by empty lines.
list.chunkedBy { it.isEmpty() }
neatly expresses that. (and yes, mostly comes up in December every year during AoC).
😁 1
m

marcinmoskala

12/29/2022, 8:00 AM
Hmm, that does make sense
18 Views