Virtual and abstract types

When a variable’s type combines different types under the same class hierarchy, its type becomes a virtual type. This applies to every class and struct except for Reference, Value, Int and Float. An example:

  1. class Animal
  2. end
  3. class Dog < Animal
  4. def talk
  5. "Woof!"
  6. end
  7. end
  8. class Cat < Animal
  9. def talk
  10. "Miau"
  11. end
  12. end
  13. class Person
  14. getter pet
  15. def initialize(@name : String, @pet : Animal)
  16. end
  17. end
  18. john = Person.new "John", Dog.new
  19. peter = Person.new "Peter", Cat.new

If you compile the above program with the tool hierarchy command you will see this for Person:

  1. - class Object
  2. |
  3. +- class Reference
  4. |
  5. +- class Person
  6. @name : String
  7. @pet : Animal+

You can see that @pet is Animal+. The + means it’s a virtual type, meaning “any class that inherits from Animal, including Animal“.

The compiler will always resolve a type union to a virtual type if they are under the same hierarchy:

  1. if some_condition
  2. pet = Dog.new
  3. else
  4. pet = Cat.new
  5. end
  6. # pet : Animal+

The compiler will always do this for classes and structs under the same hierarchy: it will find the first superclass from which all types inherit from (excluding Reference, Value, Int and Float). If it can’t find one, the type union remains.

The real reason the compiler does this is to be able to compile programs faster by not creating all kinds of different similar unions, also making the generated code smaller in size. But, on the other hand, it makes sense: classes under the same hierarchy should behave in a similar way.

Lets make John’s pet talk:

  1. john.pet.talk # Error: undefined method 'talk' for Animal

We get an error because the compiler now treats @pet as an Animal+, which includes Animal. And since it can’t find a talk method on it, it errors.

What the compiler doesn’t know is that for us, Animal will never be instantiated as it doesn’t make sense to instantiate one. We have a way to tell the compiler so by marking the class as abstract:

  1. abstract class Animal
  2. end

Now the code compiles:

  1. john.pet.talk # => "Woof!"

Marking a class as abstract will also prevent us from creating an instance of it:

  1. Animal.new # Error: can't instantiate abstract class Animal

To make it more explicit that an Animal must define a talk method, we can add it to Animal as an abstract method:

  1. abstract class Animal
  2. # Makes this animal talk
  3. abstract def talk
  4. end

By marking a method as abstract the compiler will check that all subclasses implement this method (matching the parameter types and names), even if a program doesn’t use them.

Abstract methods can also be defined in modules, and the compiler will check that including types implement them.