Kotlin List component1()
Syntax & Examples
Syntax of List.component1()
The syntax of List.component1() extension function is:
operator fun <T> List<T>.component1(): T
This component1() extension function of List returns 1st element from the list.
✐ Examples
1 Example
In this example,
- We create a list named
list
containing integers from 1 to 5. - We use the
component1
function to get the first element oflist
. - The first element is stored in
firstElement
. - We print the first element using
println
.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf(1, 2, 3, 4, 5)
val firstElement = list.component1()
println("The first element is: \$firstElement")
}
Output
The first element is: 1
2 Example
In this example,
- We create a list named
list
containing characters'a', 'b', 'c', 'd'
. - We use the
component1
function to get the first element oflist
. - The first element is stored in
firstElement
. - We print the first element using
println
.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf('a', 'b', 'c', 'd')
val firstElement = list.component1()
println("The first element is: \$firstElement")
}
Output
The first element is: a
3 Example
In this example,
- We create a list named
list
containing strings"apple", "banana", "cherry"
. - We use the
component1
function to get the first element oflist
. - The first element is stored in
firstElement
. - We print the first element using
println
.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("apple", "banana", "cherry")
val firstElement = list.component1()
println("The first element is: \$firstElement")
}
Output
The first element is: apple
Summary
In this Kotlin tutorial, we learned about component1() extension function of List: the syntax and few working examples with output and detailed explanation for each example.