Added noneOrSingle extension method, which returns a single element, null if no elements found and throws if more than one element found

This commit is contained in:
Andrius Dagys
2016-05-11 14:18:09 +01:00
parent fa3f7e7fa6
commit 2c422bebd3
3 changed files with 74 additions and 5 deletions

View File

@ -83,6 +83,33 @@ fun <T> List<T>.indexOfOrThrow(item: T): Int {
return i
}
/**
* Returns the single element matching the given [predicate], or `null` if element was not found,
* or throws if more than one element was found.
*/
fun <T> Iterable<T>.noneOrSingle(predicate: (T) -> Boolean): T? {
var single: T? = null
for (element in this) {
if (predicate(element)) {
if (single == null) {
single = element
} else throw IllegalArgumentException("Collection contains more than one matching element.")
}
}
return single
}
/** Returns single element, or `null` if element was not found, or throws if more than one element was found. */
fun <T> Iterable<T>.noneOrSingle(): T? {
var single: T? = null
for (element in this) {
if (single == null) {
single = element
} else throw IllegalArgumentException("Collection contains more than one matching element.")
}
return single
}
// An alias that can sometimes make code clearer to read.
val RunOnCallerThread = MoreExecutors.directExecutor()