Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 37 ยท Syntax and Types

Type Restrictions, Casting and Type Checks

Learn how to add type restrictions to Crystal method parameters, check types with is_a? and responds_to?, cast with as and as?, and use typeof, alias and type aliases safely.

Crystal infers most types, but you can and often should state them where they matter: on method parameters, return values and instance variables. Type restrictions make code self-documenting, give better error messages and let the compiler enforce a contract. This lesson also covers checking a type at run time, casting with as, and aliases.

Crystal listings are read-only on this site, and Ruby stand-ins are runnable. Ruby has no compile-time types, so the stand-ins perform run-time checks, which is exactly the work Crystal's compiler does for you.

Type restrictions on parameters

A restriction follows the parameter name after a colon.

CRYSTAL
def greet(name : String, times : Int32)
  times.times { puts "Hello, #{name}!" }
end

greet("Ada", 2)     # works
greet("Ada", "2")   # compile error

The error message states which argument was wrong:

TEXT
Error: expected argument #2 to 'greet' to be Int32, not String

Without restrictions the method would be compiled for whatever you pass, and the mistake might show up later, inside the body, with a less friendly message.

You can restrict to a union, to a class and all its subclasses, or to a generic type:

CRYSTAL
def show(value : Int32 | String)
  puts value
end

def total(numbers : Array(Int32)) : Int32
  numbers.sum
end

def log(message : Object)   # any object
  puts message
end

A restriction on a return type (after the closing parenthesis) makes the compiler check that every path of the method returns that type:

CRYSTAL
def half(n : Int32) : Float64
  n / 2
end

If the last expression had been a String, the build would fail. Return types are optional, but on public methods they are a free, always-correct form of documentation.

Restricting to a type, not an instance: Class

To accept a type itself as an argument, use T.class:

CRYSTAL
def build(kind : String.class, text : String)
  kind.new(text)
end

Int32.class, Float64.class and so on are the types of the types. This is useful for factories and for the generics lesson later.

Checking types at run time

When a value might be one of several types, check before using type-specific methods:

CRYSTAL
def shout(x : Int32 | String)
  if x.is_a?(String)
    x.upcase + "!"
  else
    (x * 2).to_s
  end
end

puts shout("hi")   # HI!
puts shout(21)     # 42

Three related checks:

Check Question it answers
x.is_a?(T) Is x an instance of T (or a subclass)?
x.nil? Is x nil?
x.responds_to?(:name) Does x have a method called name? (known at compile time)

responds_to? is answered by the compiler for the types involved, and narrows too:

CRYSTAL
def length_of(x : String | Int32)
  if x.responds_to?(:size)
    x.size       # here x is String
  else
    0
  end
end

The Ruby stand-in uses the run-time equivalents. Ruby's respond_to? and is_a? work the same way but are only evaluated when the line executes:

Ruby Stand-in: is_a? and respond_to? 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.

Casting with as and as?

Sometimes you know more than the compiler. as tells it: "treat this as that type; if I am wrong, raise".

CRYSTAL
items = [1, "two", 3]            # Array(Int32 | String)
first = items[0].as(Int32)       # Int32 (raises TypeCastError if it is not)
puts first + 1                   # 2

as? returns nil instead of raising, so the result is a union with Nil, and you handle it as in the previous lesson:

CRYSTAL
number = items[1].as?(Int32)     # nil: "two" is not an Int32
puts number.inspect              # nil

Compare these with converting: as does not change the data, it only asserts the type. "5".as(Int32) fails, it does not parse. To convert, use to_i, to_s, to_f and friends (see numbers).

Ruby Stand-in: a checked cast helper 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.

Use as? or an is_a? check when failure is normal, and as only when failure would be a bug.

typeof and .class

CRYSTAL
x = rand < 0.5 ? 1 : "one"
puts typeof(x)    # (Int32 | String)  -- known at compile time
puts x.class      # Int32 or String   -- known only at run time

typeof(expr) never evaluates the expression; it asks the compiler. It can appear in type positions, which is handy in generic code:

CRYSTAL
numbers = [1, 2, 3]
copy = [] of typeof(numbers.first)   # Array(Int32)

Type aliases

Long union types are tiresome to repeat. Give them a name with alias:

CRYSTAL
alias Id = Int32 | String
alias Matrix = Array(Array(Float64))

def find(id : Id) : String
  "record #{id}"
end

puts find(7)
puts find("abc")

An alias is only another name for the same type; it does not create a new one.

Nilable and default parameters

You can combine a restriction with a default and with nil:

CRYSTAL
def label(text : String, suffix : String? = nil) : String
  suffix ? "#{text} #{suffix}" : text
end

puts label("Total")          # Total
puts label("Total", "(USD)") # Total (USD)

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does def f(x : Int32) do when you call f("a")?

    A type restriction is checked by the compiler, so the program does not build.
  2. 2. What is the difference between x.as(Int32) and x.as?(Int32)?

    as raises TypeCastError when the type is wrong; as? gives nil, which you handle.
  3. 3. Does "5".as(Int32) parse the text into a number?

    Casting never changes the data. Conversion methods like to_i do.
  4. 4. What does alias Id = Int32 | String create?

    An alias is a name for an existing type, nothing more.

Summary

  • Restrict parameters and return values with name : Type; errors then point at the call site.
  • is_a?, nil? and responds_to? check types and narrow them inside the branch.
  • as asserts a type and raises if wrong; as? returns nil; neither converts data.
  • typeof is answered at compile time, .class at run time.
  • Use alias to name long unions.

Next: Conditionals and case