build List
inline fun <E> buildList(builderAction: MutableList<E>.() -> Unit): List<E>
Content copied to clipboard
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.
Since Kotlin
1.3
Samples
import samples.*
fun main() {
//sampleStart
val x = listOf('b', 'c')
val y = buildList() {
add('a')
addAll(x)
add('d')
}
assertPrints(y, "[a, b, c, d]")
//sampleEnd
}
inline fun <E> buildList(capacity: Int, builderAction: MutableList<E>.() -> Unit): List<E>
Content copied to clipboard
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.
Since Kotlin
1.3
Samples
import samples.*
fun main() {
//sampleStart
val x = listOf('b', 'c')
val y = buildList(x.size + 2) {
add('a')
addAll(x)
add('d')
}
assertPrints(y, "[a, b, c, d]")
//sampleEnd
}
Throws
if the given capacity is negative.