iyi

Playground · Methods and traits · 26 of 33

unions

Union types: a value that is one of several types.

samples/tour/unions.iyi · unions.wasm · 131 KB
# Union types: a value that is one of several types.

# `Int32 | String` holds either. Nothing is wrapped or boxed.
def parse(text : String) : Int32 | String
  n = text.to_i?
  n ? n : "not a number: #{text}"
end

# `case ... in` must name every member, so a new member in the union
# turns every incomplete `case` into a compile error.
["12", "x", "7"].each do |text|
  case parse(text)
  in Int32  then puts "number #{it * 2}"
  in String then puts "problem, #{it}"
  end
end

# `is_a?` asks, and narrows inside the `if`.
value = parse("5")
if value.is_a?(Int32)
  puts value + 1
end

# `String?` from the nil lesson is the same idea: `String | Nil`.
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 unions.wasm, the module the compiler built from this file, in your browser. How this works

Try it on your machine

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

sh, after installing
$ iyi run unions.iyi