How can I use a composite key in Kotlin?

In Python, I can have complex dictionary keys, for example:

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

How can I announce and fill out such a card in Kotlin?

Edit: I tried to declare such a Card, but I do not know how to fill it in:

val my_map = HashMap<Pair<Int, Int>, Int>()
+4
source share
2 answers

Simply, first create a 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

etc.:)

+4
source

Kotlin, unlike Python, does not have a tuple data type. There is a Pair class for two tuples. For greater significance, you should use data classes.

val map: HashMap<Pair<Int, Int>, Int> = hashMapOf(Pair(1, 2) to 3)
val nullable: Int? = map[Pair(1, 2)]
val notNullable = map.getValue(Pair(1, 2))
+1
source

Source: https://habr.com/ru/post/1687801/


All Articles