Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin - creating a mutable list with repeating elements

Tags:

list

kotlin

What would be an idiomatic way to create a mutable list of a given length n with repeating elements of value v (e.g listOf(4,4,4,4,4)) as an expression.

I'm doing val list = listOf((0..n-1)).flatten().map{v} but it can only create an immutable list.

like image 255
Basel Shishani Avatar asked Apr 02 '17 20:04

Basel Shishani


People also ask

How do you create a immutable list on Kotlin?

Kotlin has two types of lists, immutable lists (cannot be modified) and mutable lists (can be modified). Read-only lists are created with listOf() whose elements can not be modified and mutable lists created with mutableListOf() method where we alter or modify the elements of the list.


1 Answers

Use:

val list = MutableList(n) {index -> v} 

or, since index is unused, you could omit it:

val list = MutableList(n) { v } 
like image 196
voddan Avatar answered Oct 20 '22 15:10

voddan