toNotEmptyListOrThrow
@ExperimentalSinceKotoolsTypes(version = "4.3.1")
Returns a NotEmptyList containing all the elements of this collection, or throws an IllegalArgumentException if this collection is empty.
var collection: Collection<Int> = listOf(1, 2, 3)
var result: NotEmptyList<Int> = collection.toNotEmptyListOrThrow()
println(result) // [1, 2, 3]
collection = emptyList()
collection.toNotEmptyListOrThrow() // IllegalArgumentException
Content copied to clipboard
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.toNotEmptyListOrThrow()
println(original) // [1, 2, 3]
println(notEmptyList) // [1, 2, 3]
original.clear()
println(original) // []
println(notEmptyList) // [1, 2, 3]
Content copied to clipboard
You can use the toNotEmptyListOrNull function for returning null
instead of throwing an IllegalArgumentException when this collection is empty.