Skip to content
This repository has been archived by the owner on Nov 10, 2017. It is now read-only.

Functions

asterite edited this page Aug 27, 2011 · 1 revision

Functions in Crystal don't need to declare their argument and return types. When you define a function it's syntax is checked but nothing else. You can think of them as C++ or D templates where the return type will be inferred and the argument types will be deduced at the invocation moment.

So for example, the identity function:

def identity(x)
  x
end

Invoking the identity function with an Int:

identity 1

will instantiate the identity function with x being an Int, like so (in a pseudo notation):

 def identity<Int>(x)
   x
 end

Since x is the last expression in the function and it's type is Int, identity's return type is Int.

Similarly, invoking the identity function with a float will instantiate the function with x being a Float, and it's return type will be a Float.

identity 1.0

def identity<Float>(x)
  x
end
Clone this wiki locally