Maps in Kotlin
Maps are Kotlin’s built-in associative data type (sometimes called hashes or dicts in other languages).
To create an empty map, use the built-in mutableMapOf<KeyType, ValueType>()
:
Set key/value pairs using typical name[key] = val
syntax.
Printing a map with e.g. println
will show all of its key/value pairs.
Get a value for a key with name[key]
.
If the key doesn’t exist, the operation returns null
in Kotlin.
The built-in size
property returns the number of key/value pairs when called on a map.
To remove key/value pairs from a map, use the remove
function.
To remove all key/value pairs from a map, use the clear
function.
The optional second return value when getting a value from a map indicates if the key was present in the map. This can be used to disambiguate between missing keys and keys with null
values. Here we didn’t need the value itself, so we just check for the presence.
You can also declare and initialize a new map in the same line with this syntax.
Note that Kotlin does not have a built-in map utility package like maps
, but you can use standard collection functions for most operations.
Note that maps appear in the form map[k=v, k=v]
when printed with println
.
Next example: Functions.