How to create and populate Kotlin lists (initialize mutable and immutable lists)

If you ever need to create and populate a Kotlin list, I can confirm that these approaches work for an immutable and mutable lists:

// fill an immutable list
val doubles = List(5) { i -> i * 2 }

// fill a mutable list of ten elements with zeros
val ints = MutableList(10) { 0 }

The Kotlin REPL shows how these approaches work:

> val doubles = List(5) { i -> i * 2 }
> doubles
[0, 2, 4, 6, 8]

> val ints = MutableList(10) { 0 }
> ints
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

If you ever need to populate/initialize a Kotlin list when you create it, I hope these examples area helpful.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.