Kotlin List toList()
Syntax & Examples
Syntax of toList()
The syntax of List.toList() extension function is:
fun <T> Iterable<T>.toList(): List<T>
This toList() extension function of List returns a List containing all elements.
✐ Examples
1 Example
In this example,
- We create a set named
set1
containing the characters'a', 'p', 'p', 'l', 'e'
. - We convert
set1
to a List using thetoList()
function. - The resulting List, which contains all elements from the set, is stored in
list1
. - Finally, we print
list1
to standard output.
Kotlin Program
fun main(args: Array<String>) {
val set1 = setOf("a", "p", "p", "l", "e");
val list1 = set1.toList();
println(list1);
}
Output
[a, p, l, e]
2 Example
In this example,
- We create an array named
array
containing integers10, 20, 30
. - We convert
array
to a List using thetoList()
function. - The resulting List, which contains all elements from the array, is stored in
list2
. - Finally, we print
list2
to standard output.
Kotlin Program
fun main(args: Array<String>) {
val array = arrayOf(10, 20, 30);
val list2 = array.toList();
println(list2);
}
Output
[10, 20, 30]
3 Example
In this example,
- We create a string named
string
containing the characters'example'
. - We convert
string
to a List using thetoList()
function. - The resulting List, which contains all characters from the string, is stored in
list3
. - Finally, we print
list3
to standard output.
Kotlin Program
fun main(args: Array<String>) {
val string = "example";
val list3 = string.toList();
println(list3);
}
Output
[e, x, a, m, p, l, e]
Summary
In this Kotlin tutorial, we learned about toList() extension function of List: the syntax and few working examples with output and detailed explanation for each example.