first

리스트의 첫번째 값을 가져온다. 없는경우 에러.

public fun <T> Iterable<T>.first(): T {
    when (this) {
        is List -> return this.first()
        else -> {
            val iterator = iterator()
            if (!iterator.hasNext())
                throw NoSuchElementException("Collection is empty.")
            return iterator.next()
        }
    }
}


val list = listOf(1, 2, 3, 4, 5)
println(list.first())  // 1
println(listOf<Int>().first)  // Error

// 주어진 식에 맞는것 중 첫번째를 가져온다 
public inline fun <T> Iterable<T>.first(predicate: (T) -> Boolean): T {
    for (element in this) if (predicate(element)) return element
    throw NoSuchElementException("Collection contains no element matching the predicate.")
}


val list = listOf(1, 2, 3, 4, 5)
println(list.first{ it > 3 })  // 4 
println(list.first{ it > 7 })  // Error

Last updated