Search code examples
listkotlinimmutabilityidioms

More idiomatic way to initialize this kotlin list?


I want to have an immutable list, since I don't really need the mutability so it likely to just cause bugs. However, the list is a lateinit var declared at the class level.

I want to initially populate the list with values from a loop somewhat like this:

for (items in someOtherCollection) {
    val itemToAdd = doSomeProcessingOnThisData()
    list.add(itemToAdd)
}

However, since the list is immutable, I can't call add(). Is there a better way to init a list such as this without simply adding all the values to a second, mutable list and then assigning it to an immutable list?

My current solution is this, but it just seems inefficient:

val tmpList = mutableListOf<Data>()
foos.forEach() {
    val itemToAdd = doSomeProcessing()
    foos.add(itemToAdd)
}
this.list = tmpList

Solution

  • If you want to make a new list processing some data in another collection, try this:

    this.list = someOtherCollection.map {
        doSomeProcessing()
    }
    

    Give this a read for a better understanding: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/map.html