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

Indexed access


Kotlin makes it easier to access the elements of a list or return the values for a key when it comes to a map. There is no need for you to employ the Java-style syntax get(index) or get(key), but you can simply use array-style indexing to retrieve your items:

    val capitals = listOf("London", "Tokyo", "Instambul", "Bucharest") 
    capitals[2]   //Tokyo 
    //capitals[100] java.lang.ArrayIndexOutOfBoundException 
 
    val countries = mapOf("BRA" to "Brazil", "ARG" to "Argentina",  "ITA" to "Italy") 
    countries["BRA"]   //Brazil 
    countries["UK"]    //null 

While it saves you a few keystrokes, I find this construct a lot clearer to read. But nothing is stopping you from falling back to the .get method.

The preceding syntax is only available in Kotlin, and the reason it works lies in the interface declaration for List and Map. They were listed at the beginning of this chapter. There you can find the following definition:

    //list ...