Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin declare list of same values of fixed size

Tags:

list

kotlin

Is it possible to declare a list of same values of fixed size in Kotlin. For example, if the value is 1 and the size is 5. I want to declare a list which would look like below:

[1, 1, 1, 1, 1]

I know I can declare a mutable list, and then populate it with 1's. But is there any shortcut? Thanks in advance.

like image 450
Md Golam Rahman Tushar Avatar asked Nov 25 '25 05:11

Md Golam Rahman Tushar


2 Answers

easier solution for this, (just as @deHaar answer but immutable one)

List(5) { 1 }

// -> [1, 1, 1, 1, 1]
like image 138
Ebrahim Byagowi Avatar answered Nov 27 '25 22:11

Ebrahim Byagowi


I think you can just specify the amount of items and the value of each item like this:

fun main(args: Array<String>) {
    // specify the list size
    val n = 5
    // specify the item value
    val v = 1
    // create a list of size n with v as each value
    var myList = MutableList(n) {v}
    // print it
    println(myList)
}

The output is then

[1, 1, 1, 1, 1]
like image 40
deHaar Avatar answered Nov 28 '25 00:11

deHaar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!