drop
and dropWhile
are extension functions on Iterable
;
while dropLast
and dropLastWhile
are extension functions on List
What’s the reason behind making dropLast
/dropLastWhile
an extension function on List
, but not the superclass Iterable
instead?
(similarly, for takeLast
and take
)
(1.8.21)
dropLast
public fun <T> List<T>.dropLast(n: Int): List<T> {
require(n >= 0) { "Requested element count $n is less than zero." }
return take((size - n).coerceAtLeast(0))
}
public fun <T> Iterable<T>.drop(n: Int): List<T> {
require(n >= 0) { "Requested element count $n is less than zero." }
if (n == 0) return toList()
val list: ArrayList<T>
if (this is Collection<*>) {
val resultSize = size - n
if (resultSize <= 0)
return emptyList()
if (resultSize == 1)
return listOf(last())
list = ArrayList<T>(resultSize)
if (this is List<T>) {
if (this is RandomAccess) {
for (index in n until size)
list.add(this[index])
} else {
for (item in listIterator(n))
list.add(item)
}
return list
}
}
else {
list = ArrayList<T>()
}
var count = 0
for (item in this) {
if (count >= n) list.add(item) else ++count
}
return list.optimizeReadOnlyList()
}