createOrNull

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

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

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

val collection: Collection<Int> = listOf(1, 2, 3)
val elements: NotEmptyList<Int>? =
NotEmptyList.createOrNull(collection)
println(elements) // [1, 2, 3]

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

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

val original: MutableCollection<Int> = mutableListOf(1, 2, 3)
val notEmptyList: NotEmptyList<Int>? =
NotEmptyList.createOrNull(original)
println(original) // [1, 2, 3]
println(notEmptyList) // [1, 2, 3]

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

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