create
@ExperimentalSince(version = KotoolsTypesVersion.V4_5_0)
Creates a NotEmptyList containing all the elements of the specified collection, or throws an IllegalArgumentException if the 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 isSuccess: Boolean = try {
NotEmptyList.create(collection)
true
} catch (exception: IllegalArgumentException) {
false
}
assertTrue(isSuccess)
Content copied to clipboard
The NotEmptyList type being an inline value class, this method 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.create(original)
assertEquals(expected = "$original", actual = "$notEmptyList")
original.clear()
assertNotEquals(illegal = "$original", actual = "$notEmptyList")
Content copied to clipboard
You can use the NotEmptyList.Companion.createOrNull method for returning null
instead of throwing an exception in case of invalid collection.