Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 37 ยท Syntax and Types

Union Types and nil Safety

Learn how Crystal union types and the Nil type work, how the compiler narrows types with if, is_a?, case and try, and how to avoid null errors completely.

The headline feature that separates Crystal from Ruby is how it treats nil. In many languages any reference may be null, and calling a method on null crashes the program at run time. In Crystal, nil is a value of its own type, Nil, and the compiler tracks exactly where it can appear. You cannot forget to check it, because the program will not compile.

Crystal listings here are read-only. Ruby stand-ins show the run-time checks that Crystal moves to compile time, and say what Ruby does differently.

What is a union type?

A union type says "this is one of several types". It is written with a vertical bar.

CRYSTAL
def read_number(text : String) : Int32 | Nil
  text.to_i?
end

value = read_number("42")
puts typeof(value)    # (Int32 | Nil)

Int32 | Nil is so common that it has a shorthand: Int32?. The following definitions are identical:

CRYSTAL
def a : Int32 | Nil; end
def b : Int32?;      end

Unions appear everywhere: a method that may return a value or nothing, a variable assigned in different branches, an array holding mixed items like [1, "two", 3.0] (of type Array(Int32 | String | Float64)).

The compiler stops unsafe calls

CRYSTAL
value = "42".to_i?
puts value + 1

This does not compile. Because value may be Nil, the compiler says that Nil has no method +. You must prove that value is not nil before using it. The ways to do so are the heart of this lesson.

Narrowing with if

The simplest check is truthiness. nil and false are falsey; everything else is truthy.

CRYSTAL
value = "42".to_i?
if value
  puts value + 1      # here value is Int32
else
  puts "not a number"
end

Inside the if branch the compiler knows value is Int32, and in the else branch it knows it was nil (or false). This is called flow typing, or narrowing.

More explicit forms exist:

CRYSTAL
if value.nil?
  puts "nothing"
end

if value.is_a?(Int32)
  puts value * 2
end

is_a? works with any type, not only Nil, and it narrows exactly like if value.

Here is the Ruby stand-in. Ruby has no compiler check, so nil + 1 would fail only when this code runs. The code below does the explicit run-time checks that Crystal forces you to write:

Ruby Stand-in: handling nil by hand 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.

Narrowing with case and when

case can branch on type. Each when narrows the variable inside its body:

CRYSTAL
def describe(x : Int32 | String | Nil)
  case x
  when Int32
    "number #{x + 1}"
  when String
    "text #{x.upcase}"
  when Nil
    "nothing"
  end
end

puts describe(5)        # number 6
puts describe("hi")     # text HI
puts describe(nil)      # nothing

If you leave out a type the union could be, the result simply has an extra Nil in its type, because a missing branch returns nil. Using else makes the result complete.

Helpers for nil

Writing if value everywhere is tiring, so the standard library offers shortcuts:

Tool Meaning Example
try Run the block only when not nil name.try(&.upcase)
|| Fallback value value || 0
not_nil! Assert it is not nil, raise if it is value.not_nil!
?.-style chain with try Safe navigation user.try(&.address).try(&.city)
if (x = expr) Assign and test if (n = text.to_i?) ...
CRYSTAL
name = nil
puts name.try(&.upcase)        # (prints empty line; try returned nil)
puts (name || "guest")         # guest

n = "10".to_i?
puts n.not_nil! + 1            # 11, but would raise if n were nil

not_nil! silences the compiler by turning an unchecked guess into a run-time check. Use it sparingly, for cases where you really know the value exists.

There is one subtle rule: narrowing works on local variables. It does not work on instance variables or method calls, because those might change between the check and the use.

CRYSTAL
class Box
  @item : Int32? = 5

  def double
    # puts @item + 1       # compile error: @item might be nil
    if (item = @item)
      puts item + 1        # works: item is a local copy
    end
  end
end

Copying into a local (item = @item) is the standard solution, and if (item = @item) does both steps in one line.

Mixed collections

CRYSTAL
mixed = [1, "two", 3.0, nil]
puts typeof(mixed)    # Array(Float64 | Int32 | String | Nil)

mixed.each do |item|
  case item
  when Int32   then puts "int #{item}"
  when String  then puts "string #{item}"
  when Float64 then puts "float #{item}"
  when Nil     then puts "nil"
  end
end

The compiler orders the union types in its own way when it prints them, so do not rely on the order you wrote.

Why unions do not slow you down

A value of type Int32 | Nil is stored with a small type tag next to the number, a few bytes, with no heap allocation. Unions of only reference types, like String | Nil, can even use a null pointer for Nil. This design is the "zero-cost" alternative to Ruby's everything-can-be-nil model.

Ruby Stand-in: a type-tagged value 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.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the shorthand for String | Nil?

    A trailing question mark means the type or Nil.
  2. 2. Why does "42".to_i? + 1 fail to compile?

    The compiler refuses to call a method on a value that might be nil until you check it.
  3. 3. Inside if value where value is Int32?, what is the type of value?

    The truthiness check narrows the local variable to Int32 inside the branch.
  4. 4. Why does narrowing not work directly on an instance variable such as @item?

    Assigning item = @item inside the if gives a stable local the compiler can narrow.

Summary

  • A union type A | B means "one of these types"; T? is T | Nil.
  • The compiler rejects method calls that might hit nil, so null-pointer crashes disappear.
  • Narrow with if, is_a?, case/when or an assignment inside the condition.
  • Use try, || and (rarely) not_nil! as shortcuts.
  • Narrowing works on locals; copy instance variables into locals first.

Next: Type Restrictions, Casting and Type Checks