toNotEmptySetOrThrow

@ExperimentalSinceKotoolsTypes(version = "4.3.1")
fun <E> Collection<E>.toNotEmptySetOrThrow(): NotEmptySet<E>

Returns a NotEmptySet containing all the elements of this collection, or throws an IllegalArgumentException if this collection is empty.

var collection: Collection<Int> = setOf(1, 2, 3, 1)
var result: NotEmptySet<Int> = collection.toNotEmptySetOrThrow()
println(result) // [1, 2, 3]

collection = emptySet()
collection.toNotEmptySetOrThrow() // IllegalArgumentException

Please note that changes made to the original collection will not be reflected on the resulting NotEmptyList.

val original: MutableCollection<Int> = mutableSetOf(1, 2, 3, 1)
val notEmptySet: NotEmptySet<Int> = original.toNotEmptySetOrThrow()
println(original) // [1, 2, 3]
println(notEmptySet) // [1, 2, 3]

original.clear()
println(original) // []
println(notEmptySet) // [1, 2, 3]

You can use the toNotEmptySetOrNull function for returning null instead of throwing an IllegalArgumentException when this collection is empty.