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.
easier solution for this, (just as @deHaar answer but immutable one)
List(5) { 1 }
// -> [1, 1, 1, 1, 1]
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With