Home > OS >  How to use index in mapOf
How to use index in mapOf

Time:10-31

In python I can use

X = {A: "Apple", B: "Banana"}
print(x.value[0]) //Apple

In kotlin can i use ?

println(x.value[0]) // Apple

CodePudding user response:

Maps in Kotlin aren't meant to be accessed by index, so you can't do that directly. They do store entries in the order they're added (with the default Map types) which means you can convert them into an Iterable and get the first item, or whatever

val fruits = mapOf("A" to "Apple", "B" to "Banana")
// access values directly, use first() for readability
println(fruits.values.first())
// access elements, use an index, pull the value out of the entry
println(fruits.entries.elementAt(1).value)
// etc

Those properties just create an ordered Set of the entries, values etc, so you're just creating another container with a view of the existing objects.

  • Related