How to transform HashMap (mo:base) to Array?

Hi,
Attempted to use the Iter.toArray to transform a HashMap to an Array, but got the following error:

type error [M0096], expression of type
  Iter/1<(Text, Account)> = {next : () -> ?(Text, Account)}
cannot produce expected type
  {next : () -> ?Account}

When executing the source:

public func Foobar() : async [Types.Account] {
  Iter.toArray<Types.Account>(hashMap.entries());
};

For the moment, I’ve opted to iterate over the HashMap.entries and append to a local array.

Thank you!

hashMap.entries() is returning an iterator over both key and value, not just the value. So your toArray could be:

Iter.toArray<(Text, Types.Account)>(hashMap.entries());

and a function return type to match.

1 Like

@Ori thanks for helping out!

Would this be hinted at in the code editor?

I’ll double-check if my Motoko setup in VSCode (Motoko language support) is actually working properly, at the moment I’m relying on a file watcher that triggers a re-build for the particular “canister name”, where I got the error above but couldn’t figure out the right type.

For anyone else reading in the future ( I’ll check the language server docs here Language server and development client support :: Internet Computer ).

If you grab the official Motoko plugin for VSCode it will highlight compiler errors for you.

You can always use the compiler to let you know what types aren’t matching up by being explicit in all <> type parameters, this should narrow down exactly where things aren’t matching up.

Once you’ve solved any issues you can always remove these where they’re not needed for readability (Motoko will helpfully type infer in both directions in many cases, with the occasional exception).

Another simple trick you can use if you want to check what particular type a value is, is try adding it to a known type, like a Nat, and the compiler will report the type for you in the error (assuming it isn’t a Nat or subtype of a Nat).

The compiler is your friend!

1 Like

Ok, thanks for confirming that! Confirmed that the language server is failing in my local setup and I’ll have to fix it.

Sure, until now been using the watcher and the compile details to assert the code is correct or find error messages, but the language server will help more.

Thank you very much!

1 Like