Kotlin Collections First (NoSuchElementException) Or FirstOrNull (Nullable Result)

April 17, 2018

kotlin.collections first expect a result to be returned, else NoSuchElementException shall be raised.

val sku = "xxx"
try {
    val item = items.first {
        it.sku == sku
    }
}
catch (e: NoSuchElementException) {
    // do something
}

If you want a first to return null if not found, use firstOrNull.

val sku = "xxx"
val item = items.firstOrNull {
    it.sku == sku
}
if (item == null) {
    // so something
}
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.