classy_structs v0.9.0 Class View Source
The Class
module defines a few macros that provide object-oriented features, such as inheritance and polymorphism, on top of Elixir’s structs.
Additional documentation is available on the Classy structs Github page.
@author Tim Molderez
Link to this section Summary
Functions
Defines a new immutable class
Defines a new field in a class, with its default value (The default value cannot be an anonymous function.)
Call a function using dynamic dispatch
Link to this section Functions
Defines a new immutable class
The defclass macro is similar in use to defmodule, except that you can also
use var
to define fields, and extends
to specify superclasses.
Additional documentation is available on the Classy structs Github page.
Examples
defclass Animal do
var weight: 0
@abstract sound(Animal) :: String.t
end
defclass Dog do
extends Animal
var species: ""
def new(species), do
end
Defines a new field in a class, with its default value (The default value cannot be an anonymous function.)
Examples
var species: "Mammal"
var dimensions: [20, 40]
Call a function using dynamic dispatch
The function is dispatched based on the type of the first argument.
(To use static dispatch, use the .
operator instead of ~>
.)
Examples
use Class
defclass Animal do
def sound(this), do: "..."
end
defclass Cat do
extends Animal
def sound(this), do: "Meow!"
end
c = Cat.new()
Animal.sound(c) # "..."
Animal~>sound(c) # "Meow!"