Reputation: 13893
In most of the Crystal docs, class inheritance is used, with <
syntax (e.g. https://stackoverflow.com/a/61053311/2954547).
However, HTTP::Handler
says that custom handlers must include the HTTP::Handler
module and not inherit from some class.
I can't find a description in the Crystal docs of what include
-ing a module is supposed to do, or how it differs from <
-inheritance of classes.
What does it mean when a class includes a module?
Upvotes: 1
Views: 125
Reputation: 5661
Inclusion is also a form of inheritance.
The main difference is really that extending a type is limited to exactly one parent. The extension inheritance graph of the entire program is a tree. In contrast, a type can include multiple modules. And there can be multiple include inheritance paths between two types.
Upvotes: 2
Reputation: 13893
The description of inclusion is buried in the "Module" specification: https://crystal-lang.org/reference/syntax_and_semantics/modules.html
The example in the docs page is:
An include makes a type include methods defined in that module as instance methods:
module ItemsSize
def size
items.size
end
end
class Items
include ItemsSize
def items
[1, 2, 3]
end
end
items = Items.new
items.size # => 3
There is also the related extend
, which includes module members as class-level members and not instance-level members.
This is a useful way to define mixins or other namespaces, that are not meant to be instantiated as objects.
Upvotes: 0