Skip to content

Latest commit

 

History

History
138 lines (81 loc) · 3.39 KB

functions.md

File metadata and controls

138 lines (81 loc) · 3.39 KB

Functions

{id: functions}

Functions and methods

{id: functions-and-methods}

Function return value

{id: return-value} {i: return}

Function parameter passing

{id: function-parameter-passing}

Function parameter default value

{id: function-parameter-default-value} {i: default}

  • Type definition for parameters

Wrong number of arguments

{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

Any number of arguments (splat, *)

{id: any-number-of-arguments}

Manually separate

{id: manually-separate}

Tuple from

{id: tuple-from}

Array overload

{id: array-overload}

Multiple dispatch

{id: multiple-dispatch}

  • Multi-dispatch functions with same name but different signature

  • Integers are also accepted when we are expecting floats

Implicit return value

{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.

Return Type definition

{id: return-type}

  • The compile-time error only happens if we actually call the incorrect function.

Type or Nil

{id: type-or-nil} {i: ?} {i: Nil}

  • A question mark ? after the type in the function declaration is the same as accepting nil as well.
  • Int32? is the same as Int32 | ::Nil

Yield

{id: yield}

  • Optionally you can add a &anything if you think that makes the code more readable, but the important part is having yield in the code.

  • You can call yield more than once inside the function and the block will be executed for every yield.

Yield with parameters

{id: yield-with-parameters}

  • This example based on the example on the Crystal web site does not work:

Block and parameters

{id: block-and-parameters}