Update a value in a hashMap. (Value is "type")

Hi everyone!

I have created a hashMap that has as a key the userID(Principal) and as a value a “type Points”. I want to update the value by adding or removing points to the user profile.

public type UserID = Principal;

public type Points = {points: Float;}

public func updatePoints(userid: UserID, points: Points) {
hashMap.put(userid, hashMap.get(userid) + points.points);

type error, operator not defined for operand types

Hi Thanasis

The hashMap.get() method is returning an optional value ?Points , you would need to unwrap it to get a type of just Points. A safe way to do this is using a switch statement and handling the null case alongside (hashMap.get() will return null if it doesn’t find the userid you’re looking up), eg:

public func updatePoints(userid: UserID, points: Points) {
    switch(hashMap.get(userid)) {
        case(?existingEntry) {
            let updatedPoints = existingEntry.points + points.points;
            hashMap.put(userid, { points = updatedPoints });
        case(null) { 
            /* do something if it doesn't find an entry in the hashmap */

Usage for the HashMap module can be found here too, for reference: https://github.com/dfinity/motoko-base/blob/92046a6a4f6dfd8412f2b21252ad17501fee14f8/src/HashMap.mo#L66


Besides @Ori great explanation I just want to point out that whenever you have an optional return switches are exhaustive and I think it’s safe to say it behaves exactly like match in rust:

You can read more here.