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);
};
Error:
type error, operator not defined for operand types
?Points/1
and
Float
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 */
};
};
};
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: