Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 37 ยท Classes and Modules

Classes, Properties and Initialization

Create Crystal classes with initialize, instance variables, getter, setter and property macros, class methods and class variables, to_s and inspect, with Ruby stand-ins you can run.

A class bundles data with the methods that work on it. Crystal classes look like Ruby classes, but instance variables have types that the compiler tracks, and a handful of macros (getter, setter, property) remove most of the boilerplate. This lesson covers defining a class, constructors, properties, class-level members and how objects print.

Crystal listings are read-only on this site. The Ruby stand-ins run the same ideas with Ruby's attr_* helpers; differences are called out.

A first class

CRYSTAL
class Dog
  def initialize(name : String, age : Int32)
    @name = name
    @age = age
  end

  def bark
    "#{@name} says woof"
  end

  def birthday
    @age += 1
  end

  def info
    "#{@name} is #{@age}"
  end
end

rex = Dog.new("Rex", 3)
puts rex.bark       # Rex says woof
rex.birthday
puts rex.info       # Rex is 4
  • class Name ... end defines a class. Names use CamelCase.
  • initialize is the constructor. You call it with Dog.new(...).
  • @name and @age are instance variables: they belong to one object.
  • Methods run with self set to the object, so @age += 1 changes that dog.

Instance variable types

The compiler must know the type of each instance variable. It works them out from the assignments in initialize. Here @name is String and @age is Int32.

You can also declare them at the top of the class:

CRYSTAL
class Counter
  @count : Int32 = 0       # type and default value

  def increment
    @count += 1
  end

  def count
    @count
  end
end

If an instance variable might be nil at some point, include Nil in its type: @nickname : String?. Forgetting to assign a variable in initialize makes it implicitly nilable, and the compiler will make you handle that.

The shorthand def initialize(@name : String, @age : Int32) assigns the arguments to the variables directly, in one step:

CRYSTAL
class Dog
  def initialize(@name : String, @age : Int32)
  end
end

getter, setter and property

Instance variables are private to the object. To expose them, use the macros:

CRYSTAL
class Person
  getter name : String          # defines def name
  setter email : String         # defines def email=(value)
  property age : Int32          # defines both age and age=

  def initialize(@name, @email, @age)
  end
end

p = Person.new("Ada", "[email protected]", 36)
puts p.name          # Ada
p.age = 37
puts p.age           # 37
Macro Creates Use when
getter x reader x read-only from outside
setter x writer x= write-only (rare)
property x both freely readable and writable
getter? ready reader ready? Boolean flags
getter! name reader that raises if nil value is set after construction

Prefer getter and add a method that guards changes, rather than property everywhere. Fewer setters means fewer ways for an object to end up in an invalid state.

Ruby Stand-in: classes and attributes in Ruby

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

In Ruby, attr_reader and attr_accessor are methods. In Crystal getter and property are macros expanded at compile time, and they accept a type: property age : Int32.

Validation in a setter

A custom setter is an ordinary method whose name ends with =:

CRYSTAL
class Account
  getter balance : Float64 = 0.0

  def balance=(value : Float64)
    raise ArgumentError.new("balance cannot be negative") if value < 0
    @balance = value
  end
end

acct = Account.new
acct.balance = 25.0
puts acct.balance       # 25.0

Class methods and class variables

A method defined with self. belongs to the class, not to an object:

CRYSTAL
class Temperature
  def self.from_fahrenheit(f : Float64) : Float64
    (f - 32) * 5 / 9
  end
end

puts Temperature.from_fahrenheit(212.0)    # 100.0

Class-level state uses @@name, and it needs a type:

CRYSTAL
class Ticket
  @@issued = 0

  getter number : Int32

  def initialize
    @@issued += 1
    @number = @@issued
  end

  def self.issued
    @@issued
  end
end

Ticket.new
Ticket.new
puts Ticket.issued    # 2

Class variables are shared by the class and its subclasses. Treat them as global mutable state: handy for counters and caches, risky for anything else, especially once you use fibers (see the concurrency chapter).

Alternative constructors

initialize is the only constructor, but any class method can create objects. This is how you offer several ways to build one:

CRYSTAL
class Point
  getter x : Float64
  getter y : Float64

  def initialize(@x, @y)
  end

  def self.origin
    new(0.0, 0.0)
  end

  def self.polar(radius : Float64, angle : Float64)
    new(radius * Math.cos(angle), radius * Math.sin(angle))
  end
end

puts Point.origin.x    # 0.0

Printing objects: to_s and inspect

puts obj calls to_s, and p obj calls inspect. The default to_s shows the class and an address; override it for readable output:

CRYSTAL
class Dog
  def to_s(io : IO) : Nil
    io << "Dog(" << @name << ")"
  end
end

puts Dog.new("Rex", 3)    # Dog(Rex)

Note the io argument: Crystal writes into an output stream rather than building intermediate strings, which makes printing faster. inspect has the same shape. In string interpolation ("#{dog}") to_s is used too.

Equality and identity

== compares by value only if you define it; by default objects are equal only to themselves. same? and object_id test identity.

CRYSTAL
class Dog
  def ==(other : Dog)
    @name == other.@name
  end
end

For many value-like types struct and record (see structs) give you equality for free.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does property age : Int32 define?

    property creates both the getter and the setter, like Ruby's attr_accessor.
  2. 2. What does def initialize(@name : String) do?

    The @ in a parameter assigns the argument to the instance variable.
  3. 3. How do you define a class method?

    def self.name defines a method on the class itself.
  4. 4. Which method does puts obj call to get the text?

    puts uses to_s; p uses inspect.

Summary

  • A class has typed instance variables (@x), an initialize constructor and methods.
  • getter, setter and property macros generate accessors; getter? and getter! handle booleans and late-set values.
  • self. methods are class methods; @@var holds typed class-level state.
  • Offer alternative constructors with class methods that call new.
  • Override to_s(io) for readable output.

Next: Inheritance and Abstract Classes