slice() method is used to access a chunk of elements from the 'List'.
Let us take the above example, where 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.slice(1..3)) }
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 'slice()' method.
i.e. x.slice(1..3)
'x.slice(1..3)' actually tells, to pick the elements from index/position '1' to the index/position 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'.
Let us take the same example, where we have a List that contains three names, 'Mohan', 'Kriti' and 'Salim'. And we want to replace the name 'Kriti' with a new name 'Paul'.
fun main() { var x = mutableListOf("Mohan", "Kriti", "Salim") x.set(1, "Paul") println(x) }
So, in the above code we have created a 'List' using 'mutableListOf()' method, because we need to replace an element in the List.
Now, let us see, how the values are positioned in the List
Now, if we see the above diagram, 'Kriti' resides at position/index '1'. So, what we do is,use the 'set()' method specifying the position/index '1' and the new name 'Paul'.
And we get the below output,