createOrNull

@ExperimentalSince(version = KotoolsTypesVersion.V4_5_0)
fun <E> createOrNull(collection: Collection<E>): NotEmptySet<E>?

Creates a NotEmptySet containing all the elements of the specified collection, or returns null if the collection is empty.


Calling from Kotlin

Here's an example of calling this method from Kotlin code:

val collection: Collection<Int> = setOf(1, 2, 3)
val elements: NotEmptySet<Int>? = NotEmptySet.createOrNull(collection)
assertEquals(expected = "[1, 2, 3]", actual = "$elements")

The NotEmptySet type being an inline value class, this method is not available yet for Java users.

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

val original: MutableCollection<Int> = mutableSetOf(1, 2, 3)
val integers: NotEmptySet<Int>? = NotEmptySet.createOrNull(original)
assertEquals(expected = "$original", actual = "$integers")
original.clear()
assertNotEquals(illegal = "$original", actual = "$integers")

You can use the NotEmptySet.Companion.create method for throwing an exception instead of returning null in case of invalid collection.