What is the meaning of <K,V> before function parameters declaration?

Hey all

I’ve been reading source code of some of the existing smart contracts in ICP and came across something I am not sure about, if you look at this function declaration of the built in HashMap.mo library:

public func fromIter<K, V>(
    iter : Iter.Iter<(K, V)>,
    initCapacity : Nat,
    keyEq : (K, K) -> Bool,
    keyHash : K -> Hash.Hash
  ) : HashMap<K, V> {
    let h = HashMap<K, V>(initCapacity, keyEq, keyHash);
    for ((k, v) in iter) {
      h.put(k, v);

You can see there’s <K,V>(func arguments). However, return type of the function is declared after it’s parameters and I am now left wondering what does the <K, V> that preceeds function parameters even mean, why it’s there and what are the circumstances where it’s used?

Those look like generics.

I would read that as "take an iter over key of type K and value of type V, and return a hashmap over the same types, K and V.

That would allow you to write code once, with the generic types K and V, and then call this fromIter func for an interable over say nat keys and string values. And that would return a hashmap of nat keys, and string values.

If you find the resources for motoko lacking, try reading the basics on Generics in rust, as it seems to me that motoko is inspired from (and based on) rust, so the key concepts might carry over.

1 Like

I think I get it now, ty very much ser :slight_smile:

So in short, it’s made this way to enable any type for key and any type for value instead of hard coding the returned type and having to create exact same fromIter function for each of the types that we might ever need in an app?