OK, maybe not that direct. With simple types it works as may be expected:
os : Array(String | Int32) = ["abc", 123]
os.each do |o|
case o
when String
puts "String"
when Int32
puts "Int32"
else
puts "unsupported type #{typeof(o)}"
end
end
outputs
String
Int32
But for not the most simple example (but maybe more realistic):
alias K = Bytes
alias V = Bytes
alias KV = Tuple(Bytes, Bytes)
alias O = Tuple(K, Nil) |
Tuple(Nil, V) |
Tuple(KV, Nil) |
KV |
Tuple(KV, KV)
k = "k".to_slice
v = "v".to_slice
kv = {k, v}
os : Array(O) = [{k, nil},
{nil, v},
{kv, nil},
{k, v},
{kv, kv}]
os.each do |o|
case o
when Tuple(K, Nil)
puts "Tuple(K, Nil)"
when Tuple(Nil, K)
puts "Tuple(Nil, K)"
when Tuple(KV, Nil)
puts "Tuple(KV, Nil)"
when KV
puts "KV"
when Tuple(KV, KV)
puts "Tuple(KV, KV)"
else
puts "unsupported type #{typeof(o)}"
end
end
it outputs
unsupported type Tuple(Slice(UInt8) | Tuple(Slice(UInt8), Slice(UInt8)) | Nil, Slice(UInt8) | Tuple(Slice(UInt8), Slice(UInt8)) | Nil)
unsupported type Tuple(Slice(UInt8) | Tuple(Slice(UInt8), Slice(UInt8)) | Nil, Slice(UInt8) | Tuple(Slice(UInt8), Slice(UInt8)) | Nil)
unsupported type Tuple(Slice(UInt8) | Tuple(Slice(UInt8), Slice(UInt8)) | Nil, Slice(UInt8) | Tuple(Slice(UInt8), Slice(UInt8)) | Nil)
unsupported type Tuple(Slice(UInt8) | Tuple(Slice(UInt8), Slice(UInt8)) | Nil, Slice(UInt8) | Tuple(Slice(UInt8), Slice(UInt8)) | Nil)
unsupported type Tuple(Slice(UInt8) | Tuple(Slice(UInt8), Slice(UInt8)) | Nil, Slice(UInt8) | Tuple(Slice(UInt8), Slice(UInt8)) | Nil)
OK, but maybe enum will do? E.g. if I know that o is actually Tuple(K, Nil), I may just cast it to Tuple(K, Nil), can not I? Unfortunately, there is the same problem:
os.first.as Tuple(K, Nil) # Error: can't cast Tuple(Slice(UInt8) | Tuple(Slice(UInt8), Slice(UInt8)) | Nil, Slice(UInt8) | Tuple(Slice(UInt8), Slice(UInt8)) | Nil) to Tuple(Slice(UInt8), Nil)