W3cubDocs

/Kotlin

buildList

Platform and version requirements: JVM (1.3), JS (1.3), Native (1.3)
@ExperimentalStdlibApi inline fun <E> buildList(
    builderAction: MutableList<E>.() -> Unit
): List<E>

Builds a new read-only List by populating a MutableList using the given builderAction and returning a read-only list with the same elements.

The list passed as a receiver to the builderAction is valid only inside that function. Using it outside of the function produces an unspecified behavior.



fun main(args: Array<String>) {
//sampleStart
val x = listOf('b', 'c')

val y = buildList(x.size + 2) {
    add('a')
    addAll(x)
    add('d')
}

println(y) // [a, b, c, d]
//sampleEnd
}
Platform and version requirements: JVM (1.3), JS (1.3), Native (1.3)
@ExperimentalStdlibApi inline fun <E> buildList(
    capacity: Int, 
    builderAction: MutableList<E>.() -> Unit
): List<E>

Builds a new read-only List by populating a MutableList using the given builderAction and returning a read-only list with the same elements.

The list passed as a receiver to the builderAction is valid only inside that function. Using it outside of the function produces an unspecified behavior.

capacity is used to hint the expected number of elements added in the builderAction.



fun main(args: Array<String>) {
//sampleStart
val x = listOf('b', 'c')

val y = buildList(x.size + 2) {
    add('a')
    addAll(x)
    add('d')
}

println(y) // [a, b, c, d]
//sampleEnd
}

Exceptions

IllegalArgumentException - if the given capacity is negative.

© 2010–2020 JetBrains s.r.o. and Kotlin Programming Language contributors
Licensed under the Apache License, Version 2.0.
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/build-list.html