lolitsyaboixd
lolitsyaboixd

Reputation: 13

How to add values to a mutable list to then add to an immutable one

So I am using a custom SDK where I need to input a range of numbers, say from 1 to 100 as Strings into a listOf collection. Is there some efficient way this could be done with say a for loop? I barely have any experience with kotlin so all help is appreciated!

Upvotes: 0

Views: 3519

Answers (3)

Willi Mentzel
Willi Mentzel

Reputation: 29844

There is a function which looks like a constructor, but is actually top-level function. You can use it like this:

val l = List(99) { "${it + 1}" }

l will be of type List<String> (immutable).

Upvotes: 0

Joffrey
Joffrey

Reputation: 37680

You can't really "add to an immutable [list]".

If you are already using a mutable list somewhere, then you can use toList() (like in @anber's answer) to get a read-only version or you could also directly pass it to a function expecting a List (if you don't change the list while the framework is using it).

If you simply want to build an immutable list of number strings from a range of numbers, this can be achieved using basic functional operations starting from the range object itself:

val list = (1..100).map { "$it" }

Note the Kotlin range syntax here. That way you don't really have to use a for loop, and you don't even have to use a temporary mutable list. Mutable stuff is not very idiomatic in Kotlin, unless it's part of the business.

You could also use it.toString() instead of the string template, but I find it more readable with the template.

Upvotes: 2

anber
anber

Reputation: 3665

If I understand you correctly you can create mutable list, add items in loop, and then convert it to immutable list:

val mutableList = mutableListOf<String>()
for (i in 0..10) {
    mutableList.add(i.toString())
}
val immutableList = mutableList.toList()

Upvotes: 0

Related Questions