Indexed Access Operator [, ] in Kotlin
On this page (8sections)
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
How It Works
This Kotlin program demonstrates Indexed Access Operator [, ]. It first prepares the data it needs, then performs the core operation step by step, and finally prints the output shown in the Sample Output above.
- Declare the variables that hold the program’s data.
- Print the final result to the console so you can compare it with the sample output.
Try changing the input values and re-running the program to see how the output changes — this is the fastest way to understand how the logic behaves.
Frequently Asked Questions
What is Indexed Access Operator [, ] in Kotlin?
This operator replaces the ".get" method of lists and maps in Java.
How do I run this Kotlin example?
Run it in IntelliJ IDEA or Android Studio, or compile from the command line with `kotlinc file.kt -include-runtime -d file.jar` and run `java -jar file.jar`.
How can I practice Indexed Access Operator [, ]?
Copy the example into IntelliJ IDEA or Android Studio, run it, then change the values or add print statements to see how the output changes.