Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 37 ยท Classes and Modules

Generics and Enums

Write reusable typed code with Crystal generic classes and methods, then model fixed sets of choices with enums, enum methods, values and @[Flags] enums, using Ruby stand-ins you can run.

Two features finish the object-oriented toolkit. Generics let you write a class or method once and use it with many types while keeping full type safety, like Array(Int32) and Array(String). Enums model a closed set of named choices such as days of the week or HTTP methods, and integrate with case/in so the compiler can verify you covered them all.

Crystal listings are read-only here. The Ruby stand-ins reproduce the behaviour by hand (checking types at run time, using constants for enum members); Ruby has neither real generics nor enums.

Generic classes

A generic class has one or more type parameters in parentheses. By convention they are single capital letters, such as T.

CRYSTAL
class Box(T)
  getter value : T

  def initialize(@value : T)
  end

  def map(&) : Box
    Box.new(yield @value)
  end
end

int_box = Box.new(42)           # Box(Int32)
str_box = Box.new("crystal")    # Box(String)

puts int_box.value + 1          # 43
puts str_box.value.upcase       # CRYSTAL
puts typeof(int_box)            # Box(Int32)

The compiler infers T from the constructor argument, so you rarely write Box(Int32).new(42), although it is allowed and required when there is no argument to infer from (Box(String).new(...) for an empty container).

Inside Box(Int32), value is an Int32, so int_box.value + 1 is checked and fast. Passing a string where an Int32 box is expected is a compile error, which is the safety a plain Object container would give up.

You can restrict a generic parameter in a method:

CRYSTAL
def unwrap(box : Box(String)) : String
  box.value
end

Several type parameters

CRYSTAL
class Pair(A, B)
  getter first : A
  getter second : B

  def initialize(@first : A, @second : B)
  end

  def swap : Pair(B, A)
    Pair.new(@second, @first)
  end
end

p = Pair.new(1, "one")
puts typeof(p)         # Pair(Int32, String)
puts typeof(p.swap)    # Pair(String, Int32)

Generic methods

Methods are already generic when you leave their parameters untyped. When you need to name a type, use free variables with forall:

CRYSTAL
def first_or(items : Array(T), fallback : T) : T forall T
  items.empty? ? fallback : items.first
end

puts first_or([3, 4], 0)          # 3
puts first_or([] of String, "-")  # -

Here T ties the array's element type to the fallback and to the result. Passing first_or([1], "x") is an error: the element type is Int32 and the fallback is a String.

Generic structs, modules and inheritance

Structs and modules take type parameters the same way (struct Wrapper(T), module Container(T)), and a subclass can fix the parameters of its parent:

CRYSTAL
class StringBox < Box(String)
  def shout : String
    value.upcase + "!"
  end
end

Array(T), Hash(K, V), Set(T), Channel(T), Proc(*T, R) and Range(B, E) are all generic classes in the standard library.

Ruby Stand-in: a type-checked box 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.

Enums

An enum is a named set of constants, stored as integers.

CRYSTAL
enum Weekday
  Monday
  Tuesday
  Wednesday
  Thursday
  Friday
  Saturday
  Sunday
end

day = Weekday::Wednesday
puts day              # Wednesday
puts day.value        # 2  (numbering starts at 0)
puts day.wednesday?   # true  (a predicate for every member)
puts Weekday.new(4)   # Friday
puts Weekday.parse("saturday")   # Saturday (case-insensitive, raises if unknown)
puts Weekday.parse?("funday")    # nil

You can set values explicitly and choose the underlying integer type:

CRYSTAL
enum HttpStatus : Int32
  Ok       = 200
  NotFound = 404
  Error    = 500
end

puts HttpStatus::NotFound.value   # 404

Enums can have methods and constants:

CRYSTAL
enum Weekday
  def weekend? : Bool
    saturday? || sunday?
  end
end

puts Weekday::Sunday.weekend?   # true
puts Weekday::Monday.weekend?   # false

Every enum is iterable and countable:

CRYSTAL
Weekday.each { |d| print d, " " }
puts
puts Weekday.values.size    # 7

Enums with case/in

Because the members are a closed set, case ... in can check that you covered them all (see conditionals):

CRYSTAL
def mood(day : Weekday) : String
  case day
  in .monday?                  then "ugh"
  in .tuesday?, .wednesday?, .thursday? then "working"
  in .friday?                  then "almost"
  in .saturday?, .sunday?      then "free"
  end
end

puts mood(Weekday::Friday)    # almost

Add Holiday to the enum later and this method stops compiling until you handle it. Compare that with a Symbol or string where a new value would just fall through to a default.

Ruby Stand-in: enum-like constants 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.

Flags enums

Annotate an enum with @[Flags] to treat members as bits that can be combined:

CRYSTAL
@[Flags]
enum Permission
  Read
  Write
  Execute
end

mine = Permission::Read | Permission::Write
puts mine                      # Read | Write
puts mine.read?                # true
puts mine.execute?             # false
puts mine.includes?(Permission::Write)   # true
puts Permission::All           # Read | Write | Execute
puts Permission::None          # None

Each member gets a power of two (1, 2, 4), so a set of permissions fits in one integer. The compiler adds All and None automatically.

Enums versus other choices

Option Strength Weakness
enum Closed set, exhaustive case/in, cheap integer Fixed at compile time
Symbol Lightweight names No checking of spelling or completeness
String Dynamic, from input Easy to mistype, slow to compare
Class hierarchy Each member has its own data and behaviour More code

When the set is closed and known when you write the program, choose an enum.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does class Box(T) declare?

    The parentheses after the class name list type parameters.
  2. 2. What is the type of Box.new("hi") for class Box(T) with initialize(@value : T)?

    The compiler infers T from the constructor argument.
  3. 3. What does Weekday.parse?("funday") return?

    The ? form returns nil when no member matches; parse would raise.
  4. 4. What does @[Flags] change about an enum?

    Flags enums give each member a power of two so sets of members fit in one value.

Summary

  • Generic classes and structs take type parameters (Box(T)); the compiler infers them from arguments and checks every use.
  • Generic methods use forall T when you must name a type.
  • Enums define closed sets of named integer constants with predicates like monday?, value, parse and each.
  • case ... in over an enum is exhaustive, so new members cannot be forgotten.
  • @[Flags] enums combine members with | for permission-style sets.

Next: Arrays and Slices in Crystal