public fun <T> List<T>.single(): T {
return when (size) {
0 -> throw NoSuchElementException("List is empty.")
1 -> this[0]
else -> throw IllegalArgumentException("List has more than one element.")
}
}
val list = listOf(1, 2, 3, 4, 5)
val singleList = listOf(1)
val emptyList = listOf<Int>()
println(list.single()) // Error
println(singleList.single()) // 1
println(emptyList.single()) // Error