Skip to content

HashMap

Key-value store with string keys.

Methods

MethodReturnsDescription
HashMap.new()mapCreate empty map
set(key, val)Set value (string)
get(key)stringGet value ("" if missing)
has(key)boolKey exists
remove(key)Delete entry
len()intEntry count
keys()[string]Array of all keys
values()[string]Array of all values
clear()Remove all entries

Examples

wyn
m = HashMap.new()
m.set("name", "Wyn")
m.set("version", "2")

print(m.get("name"))                  // Wyn
print(m.has("name").to_string())      // true
print(m.len().to_string())            // 2

Map Literals

Build a map inline with {key: value}. Values are typed by the literal, so a map of ints yields ints back from m[k] and m.get(k):

wyn
scores = {"alice": 90, "bob": 85}
print(scores["alice"].to_string())    // 90
print(scores.get("bob").to_string())  // 85

Index and Membership

Read a value with m[key], and test for a key with in / not in:

wyn
m = {"host": "localhost", "port": "8080"}
print(m["host"])                      // localhost

if "host" in m { print("host set") }
if "user" not in m { print("no user") }

Iteration

Iterate a map directly - for k, v in m binds both key and value, and for k in m iterates the keys:

wyn
m = {"name": "Wyn", "version": "2"}

for k, v in m {
    print("${k}: ${v}")
}

for k in m {
    print(k)
}

You can also iterate the key array from keys():

wyn
for k in m.keys() {
    print("${k}: ${m.get(k)}")
}

Values

wyn
var vs = m.values()
for v in vs {
    print(v)
}

Global Access

HashMap variables can be accessed from functions:

wyn
config = HashMap.new()

fn setup() {
    config.set("host", "localhost")
    config.set("port", "8080")
}

fn get_url() -> string {
    return config.get("host") + ":" + config.get("port")
}

setup()
print(get_url())  // localhost:8080

See Also

  • Arrays - ordered collections
  • JSON - parse JSON into HashMaps
  • Database - persistent key-value storage

MIT License - v1.21.0