Immutable lists

In this section, will discuss immutable lists and their interfaces. Before going into details, however, let's have a quick look at list declaration. Kotlin provides different ways to define a list, the simplest one being the listOf keyword with comma-separated values:

val listOfInteger = listOf(1,2,3,4,5,6)
val listOfDouble = listOf(1.0,2.0,3.0,4.0,5.0,6.0)
val listOfString = listOf("One","Two","Three","Four")

The listOf keyword not only defines the list but initializes it as well. The type of the list depends on the list elements, and the size of the list depends on the number of elements that are assigned to it. We can create lists of integers and strings and display each element using a for loop:

fun listInt(){
val listOfInteger = listOf(1,2,3,4,5)
for (element in listOfInteger){
println(element)
}
}

fun listString(){
val listOfString = listOf<String>("One","Two","Three","Four","Five")
for (element in listOfString){
println(element)
}
}

Notice that the listOf function can take a declaration of an explicit type, such as listOf<String>, but this is optional. Kotlin also allows us to create a list of different data types. In the following example, we have created a list of mixed variables, called listOfEverything, which contains integers, strings, and more: 

fun listOfVararg(){
val listOfEverything = listOf(1,"Two",'c',4.0,5)
for (element in listOfEverything){
println(element)
}
}

Basically, this list is of the Any type, which is a root class in Kotlin; all classes are derived from the Any class. Using polymorphism, Kotlin allows us to add different data types in one list.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.106.135