buildSet

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.

The returned set is serializable (JVM).

Since Kotlin

1.6

Samples


fun main() { 
   //sampleStart 
   val x = setOf('a', 'b')

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

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

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.

The returned set is serializable (JVM).

Since Kotlin

1.6

Throws

if the given capacity is negative.

Samples


fun main() { 
   //sampleStart 
   val x = setOf('a', 'b')

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

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