get()
and []
Syntax
Earlier, we explored []
syntax for accessing elements in a List
, where []
would wrap a 0
-based index of the item in the list to retrieve.
We also explored using []
for accessing entries in a Map
, where []
would wrap the key for which we want to try to retrieve a value.
In reality, []
syntax is available for anything that offers a one-parameter get()
function. When Kotlin encounters []
syntax, it simply replaces that with the corresponding get()
call.
So, for example, we also saw using []
syntax to get the Nth character from a String
. String
has a get()
function, that takes a 0
-based index and returns that character from the string. When we used []
syntax (it[1] == 'o'
), Kotlin called get()
on the String
, passing in our index.
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.