subList() is used to access a chunk of elements from the 'List'.
Say, we have the 'List' with five values, 'Mohan', 'John', 'Paul', 'Kriti' and 'Salim'. And we want to access the second, third and fourth element i.e. 'John', 'Paul' and 'Kriti'.
fun main() { var x = listOf("Mohan", "John", "Paul", "Kriti", "Salim") println(x.subList(1,4)) }
So, in the above code we have created a 'List' and initialised to the variable 'x'.
Now, let us see, how the values are positioned in the List
So, as we can see the elements are positioned as '0', '1', '2', '3' and '4'.
Now, if we want to access the second, third and fourth element (i.e. 'John', 'Paul' and 'Kriti').
We can specify the range using 'subList()' method.
i.e. x.subList(1,4)
'x.subList(1,4)' actually tells, to pick the elements from index/position '1' to the index/position '4-1' i.e. 3.
And the print statement prints the second, third and fourth element (i.e. 'John', 'Paul' and 'Kriti').
So, if you look at the above output, the values are enclosed within square brackets '[]'. That is because a new array is created with the three elements 'John', 'Paul' and 'Kriti'.