Kotlin List first()
Syntax & Examples
Syntax of List.first()
There are 2 variations for the syntax of List.first() extension function. They are:
1.
fun <T> List<T>.first(): T
This extension function returns the first element.
2.
fun <T> Iterable<T>.first(predicate: (T) -> Boolean): T
This extension function returns the first element matching the given predicate.
✐ Examples
1 Example
In this example,
- We create a list named
list1
containing integers. - We use the
first()
function onlist1
to get the first element. - The first element of
list1
is stored inresult
. - Finally, we print the value of
result
to standard output using theprintln
statement.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf(1, 2, 3, 4, 5)
val result = list1.first()
println(result)
}
Output
1
2 Example
In this example,
- We create a list named
list2
containing strings. - We use the
first
function onlist2
with a predicate that finds the first string with length greater than 5. - The first string with length greater than 5 in
list2
is stored inresult
. - Finally, we print the value of
result
to standard output using theprintln
statement.
Kotlin Program
fun main(args: Array<String>) {
val list2 = listOf("apple", "banana", "cherry")
val result = list2.first { it.length > 5 }
println(result)
}
Output
banana
3 Example
In this example,
- We create a list named
list3
containing characters. - We use the
first
function onlist3
with a predicate that finds the first lowercase character. - The first lowercase character in
list3
is stored inresult
. - Finally, we print the value of
result
to standard output using theprintln
statement.
Kotlin Program
fun main(args: Array<String>) {
val list3 = listOf('a', 'b', 'c', 'd', 'e')
val result = list3.first { it.isLowerCase() }
println(result)
}
Output
a
Summary
In this Kotlin tutorial, we learned about first() extension function of List: the syntax and few working examples with output and detailed explanation for each example.