Home > Net >  Initialize list with variable number of the same value
Initialize list with variable number of the same value

Time:03-15

Is there a way to initialize a list x times with the value of y?

Thus instead of:

mutableListOf(0, 0, 0, 0)

something like:

makeMutableList(4, 0)

CodePudding user response:

Yes, just like this:

MutableList(4) { 0 }

This calls the factory function MutableList which takes a size and a lambda, passing to the lambda the index and setting the appropriate element to the result of the lambda. Thus, to create the list [1, 2, 3, 4] you can do this:

MutableList(4) { it   1 }

If you don't need a mutable list, there is also a List factory function.

When running on the JVM, both List and MutableList functions create a java.util.ArrayList, though you shouldn't rely on the exact type.

  • Related