toNotEmptyList

@Since(version = KotoolsTypesVersion.V4_0_0)
fun <E> Collection<E>.toNotEmptyList(): Result<NotEmptyList<E>>

Returns an encapsulated NotEmptyList containing all the elements of this collection, or returns an encapsulated IllegalArgumentException if this collection is empty.

Here's a simple usage example:

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

collection = emptyList()
result = collection.toNotEmptyList()
println(result) // Failure(IllegalArgumentException)

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

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