Read-only views
When working with Kotlin, you will come across the concept of a read-only view of a mutable collection. You will probably wonder what is the difference between this and an immutable collection. It is easier to understand using an example. In this case, let's create a mutable list of strings. This applies to all the collections we have covered:
val carManufacturers: MutableList<String> = mutableListOf("Masserati", "Aston Martin","McLaren","Ferrari","Koenigsegg") val carsView: List<String> = carManufacturers carManufacturers.add("Lamborghini") println("Cars View:$carsView") //Cars View: Masserati, Aston Martin, McLaren, Ferrari, Koenigsegg, Lamborghini
The code initializes a mutable list of car manufacturers and then provides a view on it via the carsView
variable. If, going forward, we only keep a reference to the latter variable, we could actually consider the...