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
Sam
05/24/2024, 9:29 AM
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
Klitos Kyriacou
05/24/2024, 9:36 AM
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
Mohammed Oucif
05/24/2024, 9:53 AM
You are correct, it does not make sense to use var with mutableList.
s
Stephan Schröder
05/24/2024, 1:12 PM
it can make sense, it's just far less common.
e
ephemient
05/24/2024, 4:05 PM
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)
}
ephemient
05/24/2024, 4:06 PM
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