How could I choose the values I want to return from type when I use "switch"?

Hi everyone!

Here is an example to help you understand what I am trying to do. I want to switch the hashMap.get(id) and to NOT return all the values of the “type” like the code below, but only some of them. For example, in this case, I want to return only the “degree” and the “name”.

case(_) {
                     switch (hashMap.get(searchID)) {
                         case(null) {return null;};
                         case(?e) {
                             return ?{
                             name = e.name;
                             surname = e.surname;
                             id = e.id;
                             degree = e.degree;
                             role = e.role;
                             }
                         };
                     };
                 };

How could I do this?

Thank you!

You’ll want to create a new type containing only the properties you want to return, and define this as the function’s return type.

1 Like

You’ll find that returning the original is still valid if you do this. This is because the new type is a subtype of the original and Motoko will strip out the extra properties when it passes out of the function. So keep an eye on these situations because it might not be what you expect.

1 Like

Thank you for your answer @Ori! Yes I think that way is working for my application!

1 Like