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...