{id: functions}
{id: functions-and-methods}
{id: return-value} {i: return}
{id: function-parameter-passing}
{id: function-parameter-default-value} {i: default}
- Type definition for parameters
{id: wrong-number-of-arguments}
- We have a function that expect two integers. Can we instead pass an array of two integers?
- Normally no, but there are at least 3 solutions
{id: any-number-of-arguments}
{id: manually-separate}
{id: tuple-from}
{id: array-overload}
{id: multiple-dispatch}
- Multi-dispatch functions with same name but different signature
- Integers are also accepted when we are expecting floats
{id: implicit-return-value}
If there is no explicit return
statement then the result of the last statement executed in the function will be
returned from the function.
{id: return-type}
- The compile-time error only happens if we actually call the incorrect function.
{id: type-or-nil} {i: ?} {i: Nil}
- A question mark
?
after the type in the function declaration is the same as acceptingnil
as well. Int32?
is the same asInt32 | ::Nil
{id: yield}
- Optionally you can add a
&anything
if you think that makes the code more readable, but the important part is havingyield
in the code.
- You can call
yield
more than once inside the function and the block will be executed for everyyield
.
{id: yield-with-parameters}
- This example based on the example on the Crystal web site does not work:
{id: block-and-parameters}