Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 37 ยท Control Flow and Methods

Overloading, Return Types and Procs

Learn how Crystal overloads methods by argument types and count, how return types are inferred and checked, and how to create, store and call procs and closures.

In Crystal you can define several methods with the same name, and the compiler picks the right one for each call from the argument types. This is method overloading, and it is checked at compile time, so it is free at run time. This lesson also covers return types and procs: functions that you can store in a variable and pass around.

Crystal listings are read-only here. Ruby cannot overload by type, so the Ruby stand-ins use case on the argument class to simulate the choice the compiler makes for you.

Overloading by type

CRYSTAL
def describe(x : Int32)
  "an integer: #{x}"
end

def describe(x : String)
  "a string: #{x}"
end

def describe(x : Array)
  "an array of #{x.size} items"
end

puts describe(5)           # an integer: 5
puts describe("hi")        # a string: hi
puts describe([1, 2, 3])   # an array of 3 items

The three methods have the same name, and each call is resolved while compiling. Calling describe(1.5) would be a compile error, because no overload accepts a Float64. If you wanted to accept it, you would add another overload or a union restriction.

Contrast this with Ruby, where one describe has to inspect the argument itself. The stand-in below shows that manual dispatch:

Ruby Stand-in: manual dispatch on type in Ruby

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Overloading by number of arguments

CRYSTAL
def area(side)
  side * side
end

def area(width, height)
  width * height
end

puts area(4)      # 16
puts area(4, 5)   # 20

You can mix type and count. A parameter with a default value also creates overload-like behaviour, because the compiler makes versions for each possible call.

Which overload wins?

When more than one overload could match, Crystal chooses the most specific one. A restriction to a concrete type is more specific than one without a restriction.

CRYSTAL
def show(x)
  "something"
end

def show(x : Int32)
  "an int"
end

puts show(1)       # an int
puts show("a")     # something

The order of definition does not matter, only specificity. If two overloads are equally specific for a call, the compiler reports that there is no unique best match when it cannot decide.

Overloading and unions

When a union value is passed, the compiler generates code that checks the real type at run time and dispatches to the matching overload. It is called dynamic dispatch on unions, and it only happens where unions exist.

CRYSTAL
value = rand < 0.5 ? 10 : "ten"
puts describe(value)    # chooses at run time between the Int32 and String versions

Return types

Return types are inferred. The compiler works out what a method returns by looking at every path.

CRYSTAL
def parse(text)
  if text == "yes"
    true
  elsif text == "no"
    false
  else
    nil
  end
end

puts typeof(parse("yes"))    # (Bool | Nil)

You can declare the type to make the compiler check it, and to keep the contract stable when the body changes:

CRYSTAL
def parse(text : String) : Bool?
  text == "yes" ? true : (text == "no" ? false : nil)
end

A method that never returns normally has the special type NoReturn. raise and exit are examples. This lets the compiler know that code after the call is not reached, and keeps the types of the other branches clean:

CRYSTAL
def positive(n : Int32) : Int32
  raise ArgumentError.new("must be positive") if n <= 0
  n
end

A method with no useful result returns nil as its last value, or you can annotate : Nil. Do not rely on the return value of puts.

Procs: functions as values

A proc is an anonymous function. Create one with ->:

CRYSTAL
add_one = ->(x : Int32) { x + 1 }

puts add_one.call(5)      # 6
puts add_one.(5)          # 6  (shorthand)
puts typeof(add_one)      # Proc(Int32, Int32)

The parameter types must be written because a proc has no surrounding call to infer from. The type Proc(Int32, Int32) means "takes an Int32 and returns an Int32", also written Int32 -> Int32.

Procs are values, so you can store them in variables, hashes and arrays and pass them to methods:

CRYSTAL
def apply(value : Int32, with_proc : Int32 -> Int32) : Int32
  with_proc.call(value)
end

double = ->(x : Int32) { x * 2 }
square = ->(x : Int32) { x * x }

puts apply(7, double)   # 14
puts apply(7, square)   # 49

Closures

A proc remembers the variables that were in scope when it was created. It is a closure.

CRYSTAL
def counter
  count = 0
  -> { count += 1 }
end

next_id = counter
puts next_id.call   # 1
puts next_id.call   # 2
puts next_id.call   # 3

The variable count lives on after counter returns, because the proc captured it. Closures are the basis of callbacks, event handlers and fibers.

Ruby Stand-in: procs and closures in Ruby

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The syntax is almost identical. The key difference is that Crystal procs have fixed types (Int32 -> Int32), which lets the compiler check every call.

Turning a method into a proc

The -> syntax can point at an existing method:

CRYSTAL
def shout(text : String) : String
  text.upcase + "!"
end

fn = ->shout(String)
puts fn.call("hey")    # HEY!

You list the parameter types so the compiler knows which overload you mean. This is helpful when you have several overloads of the same name.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. When does Crystal choose between overloads such as describe(Int32) and describe(String)?

    The compiler resolves overloads from the static types, so there is no run-time cost, except for union values.
  2. 2. If two overloads can match, which does Crystal use?

    A restriction to a concrete type is more specific than no restriction.
  3. 3. What is the type of ->(x : Int32) { x + 1 }?

    A proc type lists its argument types followed by the return type, also written Int32 -> Int32.
  4. 4. Why does a counter proc keep working after the method that created it returned?

    A closure remembers the variables from the scope where it was created.

Summary

  • Several methods may share a name; the compiler picks one by argument count and types.
  • The most specific overload wins, independent of definition order.
  • Return types are inferred, and an annotation turns them into a checked contract; NoReturn marks methods that never return.
  • A proc ->(x : T) { ... } is a typed function value; call it with .call or .().
  • Procs are closures: they keep the variables of the scope where they were made.

Next: Exceptions and Error Handling