last
리스트의 마지막 값을 반환한다
public fun <T> List<T>.last(): T {
if (isEmpty())
throw NoSuchElementException("List is empty.")
return this[lastIndex]
}
val list = listOf(1, 2, 3, 4, 5)
println(list.last()) // 5
println(listOf<Int>().last()) // Error
// 식을 만족하는 것중 마지막 값을 반환
public inline fun <T> List<T>.last(predicate: (T) -> Boolean): T {
val iterator = this.listIterator(size)
while (iterator.hasPrevious()) {
val element = iterator.previous()
if (predicate(element)) return element
}
throw NoSuchElementException("List contains no element matching the predicate.")
}
val list = listOf(1, 2, 3, 4, 5)
println(list.last{ it > 3 }) // 5
println(list.last{ it > 7 }) // Error
Last updated