Skip to content

Map ​

Native methods and properties ​

MemberSignatureBehavior
sizeusizeNumber of key-value pairs.
setset(key: K, value: V): Map<K, V>Inserts or replaces a value for a key and returns the map.
getget(key: K): V?Returns the value, or absence when the key is missing.
getOrInsertgetOrInsert(key: K, fallback: V): VReturns a mutable reference to the stored value, inserting the fallback only when the key is missing.
hashas(key: K): booleanChecks whether a key is present.
deletedelete(key: K): booleanRemoves a key and reports whether it was present.
keyskeys(): K[]Returns the keys as an array.
valuesvalues(): V[]Returns the values as an array.
entriesentries(): [K, V][]Returns key-value pairs as an array; it can also be traversed with for...of.

Map ​

tyrus
interface User {
    name: string;
    email: string;
}

const users: Map<i32, User> = Map<i32, User>();
users.set(1, { name: "Ada", email: "[email protected]" });
users.set(2, { name: "Grace", email: "[email protected]" });

const first: User? = users.get(1);
print(first?.name ?? "unknown");       // "Ada"

const exists: boolean = users.has(2);        // true
const size: usize = users.size;              // 2

for (const [id, user] of users.entries()) {
    print(`${id}: ${user.name}`);
    // 1: Ada
    // 2: Grace
}

const visits = users.getOrInsert(1, { name: "Ada", email: "[email protected]" });
// The fallback expression is evaluated only when key `1` is absent.

getOrInsert(key, value) returns a mutable reference to the value for key. The fallback expression is lazy and runs only when the key is absent.