Elye
Elye

Reputation: 60081

How to create an Immutable List that needs to loop through a field of another list

I want to create a List of item from the field within another List of items.

private var destinies: MutableList<String> = ArrayList()

fun createDestinies(sources: List<Source>) {
    for (source in sources) {
        destinies.add(source.endpoint)
    }
}

In order to do that, I need to define my destinies as MutableList, so that I could "add" to it. But I just need the "add" loop once.

Is there a way for me to do that, without need to have a MutableList? (i.e. I prefer an immutable List, since it doesn't need to change after that)

Upvotes: 0

Views: 881

Answers (1)

Elye
Elye

Reputation: 60081

Apparently quite simple as below

private var destinies: List<String> = ArrayList()

fun createDestinies(sources: List<Source>) {
    destinies = sources.map { it.endpoint }
}

Upvotes: 1

Related Questions