buildSet

Common
JVM
JS
Native
1.3
@ExperimentalStdlibApi inline fun <E> buildSet(
    builderAction: MutableSet<E>.() -> Unit
): Set<E>

(source)

Builds a new read-only Set by populating a MutableSet using the given builderAction and returning a read-only set with the same elements.

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

Elements of the set are iterated in the order they were added by the builderAction.



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

val y = buildSet(x.size + 2) {
    add('b')
    addAll(x)
    add('c')
}

println(y) // [b, a, c]
//sampleEnd
}
Common
JVM
JS
Native
1.3
@ExperimentalStdlibApi inline fun <E> buildSet(
    capacity: Int,
    builderAction: MutableSet<E>.() -> Unit
): Set<E>

(source)

Builds a new read-only Set by populating a MutableSet using the given builderAction and returning a read-only set with the same elements.

The set 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.

Elements of the set are iterated in the order they were added by the builderAction.



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

val y = buildSet(x.size + 2) {
    add('b')
    addAll(x)
    add('c')
}

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

Exceptions

IllegalArgumentException - if the given capacity is negative.