Crystal Easy · Lesson 1 · On the house

Generics: Holder(T), Stack(T) and forall

Write generic classes with a type parameter, let the compiler infer T from new, and write generic methods with forall. Lesson 1 is free — on the house.

Lessons · Crystal Easy · Lesson 1 of 10 · On the house

Generics: Holder(T), Stack(T) and forall

Write generic classes with a type parameter, let the compiler infer T from new, and write generic methods with forall.

Illustration for Crystal
Lesson 1 is on the house.

class Stack(T) declares a generic class. T is a type parameter used wherever the element type appears: @items = [] of T, def push(x : T), def pop : T?.

Instantiate with an explicit type, Stack(Int32).new, or let initialize infer it: given def initialize(@value : T), Holder.new("hi") becomes Holder(String).

Each instantiation is compiled separately, so Stack(Int32) and Stack(String) are distinct types. Pushing a String onto a Stack(Int32) is a compile error, not a runtime one.

A generic method uses a free variable: def first_of(a : Array(T)) : T forall T. The compiler binds T from the argument at each call site.

Generic parameters can be unions: Stack(Int32 | String) accepts both. Several parameters are allowed: class Pair(K, V).

Use typeof to confirm what was inferred, and T itself inside the class body when you need the element type, as in T.name.

generics

class Stack(T)
  def initialize
    @items = [] of T
  end

  def push(x : T)
    @items << x
    self
  end

  def pop : T?
    @items.pop?
  end

  def size
    @items.size
  end

  def kind
    T.name
  end
end

class Holder(T)
  getter value : T

  def initialize(@value : T)
  end
end

def first_of(a : Array(T)) : T forall T
  a[0]
end

s = Stack(Int32).new
s.push(1).push(2).push(3)
puts s.pop
puts s.size
puts s.kind
b = Holder.new("hi")
puts typeof(b)
puts typeof(Holder.new(2.5).value)
puts first_of(["x", "y"])
mixed = Stack(Int32 | String).new
mixed.push(1).push("one")
puts mixed.pop
Match this when you type.

Quiz

What type does Holder.new("hi") have when initialize takes @value : T?

Quiz

What happens if you push a String onto a Stack(Int32)?

Quiz

What does forall T do on a method?

Quiz

What does s.pop print after pushing 1, 2 and 3?

Check

Match the still for: Generics: Holder(T), Stack(T) and forall.

Open-book: the answers are on this page. Pass every quiz and check (5) to mark the lesson done. This visit: 0/5.