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