singleOrNull
public fun <T> List<T>.singleOrNull(): T? {
return if (size == 1) this[0] else null
}
val list = listOf(1, 2, 3, 4, 5)
val singleList = listOf(1)
val emptyList = listOf<Int>()
println(list.singleOrNull()) // null
println(singleList.singleOrNull()) // 1
println(emptyList.singleOrNull()) // null
public inline fun <T> Iterable<T>.singleOrNull(predicate: (T) -> Boolean): T? {
var single: T? = null
var found = false
for (element in this) {
if (predicate(element)) {
if (found) return null
single = element
found = true
}
}
if (!found) return null
return single
}
val list = listOf(1, 2, 3, 4, 5)
println(list.singleOrNull{ it > 3 }) // null
println(list.singleOrNull{ it > 4 }) // 5
println(list.singleOrNull{ it > 5 }) // null
Last updated