How can I have a composite key in Kotlin?


In Python i can have complex dictionary keys like for example:

d  {}
d[(1, 2)]  3
print d[(1, 2)]  # prints 3

How can I declare and populate such a Map in Kotlin?

Edit: I tried to declare a Map like this, but I don’t know how to populate it:

val my_map  HashMap<Pair<Int, Int>, Int>()


It’s simple, you first create your dictionary and then insert the key and values:

val (a, b):Pair<Int, String>  Pair(1, "x")

val map: HashMap<Pair<Int, String>, Int>  hashMapOf((a, b) to 1)

map[Pair(2, "y")]  3

and so on 🙂

Answered By – Damián Rafael Lattenero

Leave a Comment