https://kotlinlang.org logo
#stdlib
Title
# stdlib
y

Yacov Rosenberg

01/20/2023, 6:15 PM
Hey Guys, I was trying to solve a bug in a application here and I noticed something that seems weird to me. Basically I had this code in my application:
Copy code
fun DownloadManager.isAudiobookCompleted(isbn: String): Boolean {
    return currentDownloads
        .filter { it.audiobookIsbn == isbn }
        .all { it.state == Download.STATE_COMPLETED }
}
Very intuitive where I want to return true, but was buggy. So I went to see why and just realized how the .all works:
Copy code
/**
 * Returns `true` if all elements match the given [predicate].
 * 
 * @sample samples.collections.Collections.Aggregates.all
 */
public inline fun <T> Iterable<T>.all(predicate: (T) -> Boolean): Boolean {
    if (this is Collection && isEmpty()) return true
    for (element in this) if (!predicate(element)) return false
    return true
}
Basically when the list isEmpty, it returns true. Is't it wrong? I mean, for me it should return true only match the predicate, and if the list is empty for sure don't match the predicate...
e

ephemient

01/20/2023, 6:19 PM
for all
list
and
x
,
Copy code
(list + listOf(x)).all(predicate) == (list.all(predicate) && predicate(x))
and of course
Copy code
listOf(x).all(predicate) == predicate(x)
now, if
list == emptyList()
, the only reasonable value for
.all(predicate)
is
true
2
similarly,
emptyList().any(predicate) == false
and
emptyList().none(predicate) == true
y

Yacov Rosenberg

01/20/2023, 6:27 PM
Thank you @ephemient 🙂
i

ilya.gorbunov

01/21/2023, 3:34 PM
Sometimes I wonder if they should just leave a link to this wiki article in the .all() docstring
It is already there https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/all.html
2 Views