What is the difference between find and firstOrNull?

Given the following code extracted from Kotlin Koans :

fun Shop.findAnyCustomerFrom(city: City): Customer? {
    // Return a customer who lives in the given city, or null if there is none
    return customers.firstOrNull { it.isFrom(city) }
}

In my own solution is used customers.find. Both work in a koan script.

The documentation for firstOrNulland findseems very similar.

What is the difference between these two functions?

+4
source share
1 answer

In this 2014 thread, Kotlin community members and JetBrains employees discuss the merits of various methods findand firstOrNull:

https://youtrack.jetbrains.com/issue/KT-5185

Not yet an official expression, JetBrains employee Ilya Ryzhenkov describes this as:

, find firstOrNull. , indexOf , find " , , null, ". , , firstOrNull, singleOrNull, .

:

  • find(predicate) firstOrNull(predicate) , find firstOrNull
  • find , , Linq-style Function.

Array<out T>.find , ( , ):
https://github.com/JetBrains/kotlin/blob/1.1.3/libraries/stdlib/src/generated/_Arrays.kt#L657

@kotlin.internal.InlineOnly
public inline fun <T> Array<out T>.find(predicate: (T) -> Boolean): T? {
    return firstOrNull(predicate)
}

Sequence<T>.find:
https://github.com/JetBrains/kotlin/blob/1.1.3/libraries/stdlib/src/generated/_Sequences.kt#L74

@kotlin.internal.InlineOnly
public inline fun <T> Sequence<T>.find(predicate: (T) -> Boolean): T? {
    return firstOrNull(predicate)
}

( Kotlin, , , , , JVM - ?)

+6

Source: https://habr.com/ru/post/1683066/


All Articles