Search code examples
crystal-lang

What are < symbols in Crystal classes used for?


What is the < symbol in this class and what is its purpose?

class CommentSerializer < BaseSerializer
  def initialize(@comment : Comment)
  end

  def render
    {body: @comment.body}
  end
end

https://crystal-lang.org/api/0.33.0/Class.html#T.class):BoolforallT-instance-method

Not sure if this is correct or what it means:

Returns whether this class inherits or includes other.


Solution

  • < signifies inheritance. You should read class CommentSerializer < BaseSerializer as the class CommentSerializer being derived from or based on BaseSerializer. CommentSerializer inherits the behaviors of BaseSerializer: it gets all of its instance variables and all of its methods without having to write them out again. This idea of inheritance is common to all object oriented programming languages, as it is a useful way to express code reuse: all the things inside BaseSerializer remain the same in its subclasses, and each subclass adds stuff/makes changes to tailor that generic behavior to a specific purpose.

    The < symbol you found was a method that tests for this relationship. It's an expression, and is not the same thing as the < in the declaration (which is built into the syntax). The idea is that you defined CommentSerializer < BaseSerializer, and so the test CommentSerializer < BaseSerializer will return true. The reuse of the symbol is a mnemonic.

    Language reference