Default parameter values in Motoko

Is it possible to define a function with a default value for one or more parameters?

Something like

public func myFunc(param1: Nat, param2: Bool = false): Text

So I can make calls like

myFunc(1); // same as myFunc(1, false);
myFunc(2, true);

This results in a syntax error on the function declaration: syntax error, unexpected token '=', expected one of token or <phrase> sequence

I couldn’t find anything in the docs regarding default parameter values, so I’m assuming it’s not possible yet. Or maybe there’s a more Motoko-y way to accomplish this using variants or something.

Motoko doesn’t have defaults for parameters like that. One possibility is to use an option here:

public func myFunc(param1: Nat, param2: ?Bool): Text {
  let param2 : Bool = Option.get(param2, false);
  ...
}

and then your calls look like:

myFunc(1, null); // same as myFunc(1, ?false);
myFunc(2, ?true);

Doesn’t scale to very large parameter lists nicely, but then those are bad style anyway…

6 Likes