Fixed #KT-6476. last(predicate) and lastOrNull(predicate) use reverse iteration when possible.
This commit is contained in:
committed by
Ilya Gorbunov
parent
d81895df77
commit
f87dcff723
@@ -411,10 +411,38 @@ fun elements(): List<GenericFunction> {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if (!found) throw NoSuchElementException("Collection doesn't contain any element matching predicate")
|
||||
if (!found) throw NoSuchElementException("Collection doesn't contain any element matching the predicate.")
|
||||
return last as T
|
||||
"""
|
||||
}
|
||||
|
||||
body(Iterables) {
|
||||
"""
|
||||
if (this is List<T>)
|
||||
return this.last(predicate)
|
||||
|
||||
var last: T? = null
|
||||
var found = false
|
||||
for (element in this) {
|
||||
if (predicate(element)) {
|
||||
last = element
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if (!found) throw NoSuchElementException("Collection doesn't contain any element matching the predicate.")
|
||||
return last as T
|
||||
"""
|
||||
}
|
||||
|
||||
body(ArraysOfPrimitives, ArraysOfObjects, Lists) {
|
||||
"""
|
||||
for (index in this.indices.reversed()) {
|
||||
val element = this[index]
|
||||
if (predicate(element)) return element
|
||||
}
|
||||
throw NoSuchElementException("Collection doesn't contain any element matching the predicate.")
|
||||
"""
|
||||
}
|
||||
}
|
||||
|
||||
templates add f("lastOrNull(predicate: (T) -> Boolean)") {
|
||||
@@ -433,6 +461,33 @@ fun elements(): List<GenericFunction> {
|
||||
return last
|
||||
"""
|
||||
}
|
||||
|
||||
body(Iterables) {
|
||||
"""
|
||||
if (this is List<T>)
|
||||
return this.lastOrNull(predicate)
|
||||
|
||||
var last: T? = null
|
||||
for (element in this) {
|
||||
if (predicate(element)) {
|
||||
last = element
|
||||
}
|
||||
}
|
||||
return last
|
||||
"""
|
||||
}
|
||||
|
||||
|
||||
|
||||
body(ArraysOfPrimitives, ArraysOfObjects, Lists) {
|
||||
"""
|
||||
for (index in this.indices.reversed()) {
|
||||
val element = this[index]
|
||||
if (predicate(element)) return element
|
||||
}
|
||||
return null
|
||||
"""
|
||||
}
|
||||
}
|
||||
|
||||
templates add f("single()") {
|
||||
|
||||
Reference in New Issue
Block a user