iyi

Playground · Methods and traits · 24 of 33

dispatch

A trait is a type: one list, many kinds, one question.

samples/tour/dispatch.iyi · dispatch.wasm · 131 KB
# A trait is a type: one list, many kinds, one question.

trait Speak
  abstract def sound : String
end

struct Dog
  def initialize(@name : String)
  end

  def name : String
    @name
  end
end

struct Cat
  def initialize(@name : String)
  end

  def name : String
    @name
  end
end

impl Speak for Dog
  def sound : String
    "hav"
  end
end

impl Speak for Cat
  def sound : String
    "miyav"
  end
end

# `of Speak` types the array by the trait, so both fit.
animals = [Dog.new("Karabaş"), Cat.new("Pamuk")] of Speak
animals.each { |animal| puts animal.sound }

# A function can ask for the trait rather than a particular type.
def chorus(voices : Array(Speak)) : String
  voices.map { |v| v.sound }.join(" ")
end

puts chorus(animals)
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 dispatch.wasm, the module the compiler built from this file, in your browser. How this works

Try it on your machine

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

sh, after installing
$ iyi run dispatch.iyi