Advanced overloading
Multiple expected types
Due to overloading, an expression can have multiple expected types.
In most cases, this is basically like having no expected type, but in some cases it can matter.
Below, 1 has two expected types nat8 and string.
It chooses nat8 since a number literal can't be a string.
With no expected type, the type would have been nat instead.
Effects of left to right type checking
Since type checking works from left to right,
if you do need type annotations, it's best to put them on earlier arguments.
This gives the type checker information earlier.
More examples
Keen type-checks function calls from left to right (assuming prefix syntax). So:
- If first sees a call to
fooexpecting astring(due to the::stringat the call).
There is only onefoofunction that returns astring, so the other overload is discarded. - Then it checks the argument to
fooexpecting asymbol, since that is the parameter type of the only survivingfoooverload. - That argument is a call to
bar.
There is only onebarreturning asymbol, so the other overload is discarded. - After checking the call to
bar, it now has an argument typesymboland finishes checking the call tofoo.
The argument type matches the remainingfoo's parameter type, so it's done.
Another example:
- If first sees a call to
foo.
There are twofoofunctions, and it can't discard any based on the number of arguments or return type. - Then it checks the argument to
fooexpecting aboolorsymbol, since those are the parameter types of thefoofunctions. - That argument is a call to
bar. Only thebarreturningsymbolmatches one of the expected types.
Thebarreturningintis discarded as it can't matchboolorsymbol. - After checking the call to
bar, it now has an argument typesymboland finishes checking the call tofoo.
Since only onefoodeclares asymbolparameter, it uses that one.