Book Image

Programming Kotlin

Book Image

Programming Kotlin

Overview of this book

Quickly learn the fundamentals of the Kotlin language and see it in action on the web. Easy to follow and covering the full set of programming features, this book will get you fluent in Kotlin for Android.
Table of Contents (20 chapters)
Programming Kotlin
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Customer Feedback
Preface

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 collection to be fully immutable, hence the read-only...