toNotEmptyListOrNull

@ExperimentalSinceKotoolsTypes(version = "4.3.1")
fun <E> Collection<E>.toNotEmptyListOrNull(): NotEmptyList<E>?

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

var collection: Collection<Int> = listOf(1, 2, 3)
var result: NotEmptyList<Int>? = collection.toNotEmptyListOrNull()
println(result) // [1, 2, 3]

collection = emptyList()
result = collection.toNotEmptyListOrNull()
println(result) // null

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>? = original.toNotEmptyListOrNull()
println(original) // [1, 2, 3]
println(notEmptyList) // [1, 2, 3]

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

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