Generics

Generics allow you to parameterize a type based on other type. Consider a Box type:

  1. class MyBox(T)
  2. def initialize(@value : T)
  3. end
  4. def value
  5. @value
  6. end
  7. end
  8. int_box = MyBox(Int32).new(1)
  9. int_box.value # => 1 (Int32)
  10. string_box = MyBox(String).new("hello")
  11. string_box.value # => "hello" (String)
  12. another_box = MyBox(String).new(1) # Error, Int32 doesn't match String

Generics are especially useful for implementing collection types. Array, Hash, Set are generic types, as is Pointer.

More than one type argument is allowed:

  1. class MyDictionary(K, V)
  2. end

Any name can be used for type arguments:

  1. class MyDictionary(KeyType, ValueType)
  2. end

Type variables inference

Type restrictions in a generic type’s constructor are free variables when type arguments were not specified, and then are used to infer them. For example:

  1. MyBox.new(1) # : MyBox(Int32)
  2. MyBox.new("hello") # : MyBox(String)

In the above code we didn’t have to specify the type arguments of MyBox, the compiler inferred them following this process:

  • MyBox.new(value) delegates to initialize(@value : T)
  • T isn’t bound to a type yet, so the compiler binds it to the type of the given argument

In this way generic types are less tedious to work with.

Generic structs and modules

Structs and modules can be generic too. When a module is generic you include it like this:

  1. module Moo(T)
  2. def t
  3. T
  4. end
  5. end
  6. class Foo(U)
  7. include Moo(U)
  8. def initialize(@value : U)
  9. end
  10. end
  11. foo = Foo.new(1)
  12. foo.t # Int32

Note that in the above example T becomes Int32 because Foo.new(1) makes U become Int32, which in turn makes T become Int32 via the inclusion of the generic module.

Generic types inheritance

Generic classes and structs can be inherited. When inheriting you can specify an instance of the generic type, or delegate type variables:

  1. class Parent(T)
  2. end
  3. class Int32Child < Parent(Int32)
  4. end
  5. class GenericChild(T) < Parent(T)
  6. end