Introduce firstNotNullOf and firstNotNullOfOrNull #KT-12109

This commit is contained in:
Abduqodiri Qurbonzoda
2021-03-11 18:08:26 +03:00
parent d4b3ae92cb
commit ff5b2404af
15 changed files with 342 additions and 0 deletions
@@ -17,6 +17,36 @@ import kotlin.random.*
import kotlin.ranges.contains
import kotlin.ranges.reversed
/**
* Returns the first non-null value produced by [transform] function being applied to entries of this map in iteration order,
* or throws [NoSuchElementException] if no non-null value was produced.
*
* @sample samples.collections.Collections.Transformations.firstNotNullOf
*/
@SinceKotlin("1.5")
@kotlin.internal.InlineOnly
public inline fun <K, V, R : Any> Map<out K, V>.firstNotNullOf(transform: (Map.Entry<K, V>) -> R?): R {
return firstNotNullOfOrNull(transform) ?: throw NoSuchElementException("No element of the map was transformed to a non-null value.")
}
/**
* Returns the first non-null value produced by [transform] function being applied to entries of this map in iteration order,
* or `null` if no non-null value was produced.
*
* @sample samples.collections.Collections.Transformations.firstNotNullOf
*/
@SinceKotlin("1.5")
@kotlin.internal.InlineOnly
public inline fun <K, V, R : Any> Map<out K, V>.firstNotNullOfOrNull(transform: (Map.Entry<K, V>) -> R?): R? {
for (element in this) {
val result = transform(element)
if (result != null) {
return result
}
}
return null
}
/**
* Returns a [List] containing all key-value pairs.
*/