iyi

Playground · Methods and traits · 25 of 33

defaults

Default methods: a trait can carry bodies of its own.

samples/tour/defaults.iyi · defaults.wasm · 123 KB
# Default methods: a trait can carry bodies of its own.

trait Greet
  abstract def name : String

  # Not abstract: every implementer gets this one for free, written in
  # terms of the requirement.
  def greeting : String
    "Merhaba, #{name}!"
  end

  def shout : String
    greeting.upcase
  end
end

struct Person
  def initialize(@name : String)
  end
end

impl Greet for Person
  def name : String
    @name
  end
end

struct Robot
  def initialize(@id : Int32)
  end
end

impl Greet for Robot
  def name : String
    "unit #{@id}"
  end

  # An implementer may replace a default.
  def greeting : String
    "BEEP #{name}"
  end
end

puts Person.new("Ada").greeting
puts Person.new("Ada").shout
puts Robot.new(7).greeting
puts Robot.new(7).shout
output
Press Run.

recorded with iyi 0.18.0 (built on Crystal 1.22.0-dev [2a9653052] (2026-10-18)) · Linux 7.0.0-38-generic x86_64, QEMU Virtual CPU version 2.5+ · 2026-10-19

You can type in the pane: nothing here compiles, so what you type cannot run, and the page says which bytes it is running the moment the text stops being the recorded file. There is no standard input, no filesystem and no threads on this target, and one sample fails on purpose for exactly that reason.

Run executes defaults.wasm, the module the compiler built from this file, in your browser. How this works

Try it on your machine

Copy the program into defaults.iyi, change something, and run it. Only a compiler on your own machine can run what you wrote.

sh, after installing
$ iyi run defaults.iyi