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.


Calling from Kotlin

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

val collection: Collection<Int> = listOf(1, 2, 3)
val result: Result<NotEmptyList<Int>> = collection.toNotEmptyList()
val actual: List<Int> = result.getOrThrow()
.toList()
assertContentEquals(expected = collection, actual)

The NotEmptyList type being an inline value class, it is not recommended to call this method from Java code.

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()
assertEquals(expected = "$original", actual = "$notEmptyList")
original.clear()
assertNotEquals(illegal = "$original", actual = "$notEmptyList")