Indexed Access Operator [, ] in Kotlin


Definition

  • This operator replaces the ".get" method of lists and maps in Java.
  • The syntax of this operator is similar to that of obtaining a value from an array in Java.
  • The value at a position in a list can be obtained just by mentioning the index of the value like "variable[index]"
  • The value for a key in a map can be obtained just by mentioning the index of the value like "variable[key]"

Syntax

1. Usage in List

variable_name[index]

For example,

//Assigning the value of the item at 5th position of the list to a variable named value
var value = list[5]

2. Usage in Map

variable_name[key]

For example,

//Assigning the value of the item with key "one" of map to a variable named value
var value = map["one"]

Indexed Access Operator Example Program in Kotlin

//Indexed Access Operator Example Program in Kotlin
//Operator Kotlin Programs, Basic Kotlin Program
fun main(args: Array<String>) {
    
    //Indexed Access operator usage in a list
    val nameList = listOf("Ramesh","Suresh","Dinesh")
    println("The nameList is : $nameList" )
    println("Printing the 0th item of the nameList : ${nameList[0]}" )

    //Indexed Access operator usage in a map
    val nameMap = mapOf(1 to "Sheela",2 to "Leela", 3 to "Maala")
    println("The nameMap is : $nameMap" )
    println("Printing the item of the nameMap with key '2' : ${nameMap[2]}" )
}

Sample Output

The nameList is : [Ramesh, Suresh, Dinesh]
Printing the 0th item of the nameList : Ramesh
The nameMap is : {1=Sheela, 2=Leela, 3=Maala}
Printing the item of the nameMap with key '2' : Leela