[SOLVED] How to add a variable in sophia maps?

Hi I have a state variable defined in a smart contract as follow:

record state = {
    board: map(int, int)}

Now, I define a function to update board:

public stateful function set(key: int, val: int) : int =
    put(state.board{[key] = val})

and I get the following error:

Error data: {“reason”:“Type errors\nCannot unify state\n and map(int, int)\nwhen checking the application at line 18, column 9 of\n put : (state) => ()\nto arguments\n state.board {[10] = 1} : map(int, int)\n”}

I also tried updating the map with:

board[key] = val

but I also get error. How should I update (or add) a variable to the map?

The right way to update a map variable is using put as in the following function:

public stateful function set(key: int, val:int) : int =
  put(state{ board[key] = val })

--------------------------------------OLD ANSWER -----------------------------------------------------
It (compiles) using:

public stateful function set(key: int, val:int) : int =
  state.board{[key] = val}

but it doesn’t update variable.

1 Like

If by works you mean compile, then yes. If by works you mean update the state, then no.

You can only update the contract state by using put()

1 Like

Why it is designed that way? Isn’t it unnecessary complication?

It is indeed a design choice, we thought that from a safety perspective it is very beneficial to make it explicit where (and how) the state is updated. But as all design choices they can be questioned, however, we think this is a better way to do state updates.

That is fine. Maybe marking a function stateful would be sufficient enough. It is a matter of knowledge about background of such requirement. Without that knowledge it looks weird and unnecessary. Anyway, it is always possible to change the language to not to use put() function and that change would be backward-compatible. The other way would be not possible (like require put() later).

1 Like