Maps

A mapping of keys of a fixed value type, to values of a fixed type.

Fig 1:


var myMap: mut {string: int} = mut {};
myMap["Jason"] = 28;
print("Jason" in myMap); # true
myMap["Kenny"] = 29;
print(myMap); # mut {"Jason": 28, "Kenny": 29}

Output:

true
mut {Jason: 28, Kenny: 29}

Checking if a Key Exists

You can check for the existence of a key in a map by using the in keyword.

Fig 2:


var m = {"a": 1, "b": 2};

for (k in ["a", "b", "c"]) {
  print("{k} in map: {k in m}");
}

Output:

a in map: true
b in map: true
c in map: false

Iterating Over the Entries of a Map

Claro's for loop supports iterating over the entries of a map, with each entry modeled as tuple<K, V>:

Fig 3:


var m = {"a": 1, "b": 2};

for (entry in m) {
  var k = entry[0];
  var v = entry[1];
  print("{k} -> {v}");
}

Output:

a -> 1
b -> 2

Stdlib maps Module

A large variety of map operations are available in the stdlib's maps module. For example, you can declare a default value that will be used as fallback if the read key doesn't exist in the map by using the following function declared in the maps.claro_module_api file:

Fig 4:


# Returns the value to which the specified key is mapped, or `defaultValue` if this map contains no mapping for the key.
function getOrDefault<K,V>(m: {K:V}, k: K, defaultValue: V) -> V;

Fig 5:


var m = {"a": 1, "b": 2};

for (k in ["a", "b", "c"]) {
  print(maps::getOrDefault(m, k, -1));
}

Output:

1
2
-1