Reassigning object properties

I have an object and I’d like to change the value of one of its properties, keeping everything else the same. I assumed this would work:

type Person = {
    name: Text;
    age: Nat;
};

var mike = {
    name = "Mike";
    age = 33;
};

mike.age := 34;

I get type error, expected mutable assignment target. I get the same error when I defining the type like this:

type Person = {
    name: Text;
    var age: Nat;
};

It must be possible to change object property values after creation, but obviously not the way I’m trying to do it. I’m finding it somewhat difficult to learn simple things like this due to the lack of Motoko tutorials and examples out there.

You’d need to also add var on the property when you create the object:

type Person = {
    name: Text;
    var age: Nat;
};

let mike = {
    name = "Mike";
    var age = 33;
};

You can get the compiler to help with things like this by explicitly declaring the object as the type you want it to be:

let mike: Person = {
    name = "Mike";
    var age = 33;
};

Missing the var here would then have told you that the types didn’t match.

2 Likes

Thanks Ori, I was just posting the same reply!

3 Likes