Hello everybody, I hope you are doing well. We all know that we have mutable and immutable lists tha...
m
Hello everybody, I hope you are doing well. We all know that we have mutable and immutable lists that can be assigned to either val or var variables but do we really have a case where we want to use val items = mutableListOf<String>(). Do you know a case where we want to prevent the changing of the list instance but still can make changes to it ?
s
Let me turn the question around. Do you have a case where you really want to allow changing both the contents of the list and the variable that points to it? In my mind that would be pretty confusing, and could make it quite unclear how the list is supposed to be used.
3
k
Your phrase "prevent the changing of the list instance" sounds confusing. A
val
doesn't "prevent the changing of the list instance". The instance itself can be changed (modified). It's the variable that points to the instance that can't be changed to point to another instance.
🤝 1
m
You are correct, it does not make sense to use var with mutableList.
s
it can make sense, it's just far less common.
e
Copy code
fun <E> Iterable<E>.groupConsecutiveBy(predicate: (E, E) -> Boolean): List<List<E>> = buildList {
    var group = mutableListOf<E>()
    for (item in this@groupConsecutiveBy) {
        if (group.isEmpty() || predicate(group.last(), item)) {
            group.add(item)
        } else {
            if (group.isNotEmpty()) add(group)
            group = mutableListOf(item)
        }
    }
    if (group.isNotEmpty()) add(group)
}
that could be done with a
fold
but either having a mutable accumulator is the same sort of weirdness - usually you don't want it, but sometimes it's the right solution