What is the best practice to do something such as
local
l_pet: ANIMAL
do
l_pet := catch_it_from_the_sky
inspect l_pet
when attached {DOG} l_pet as l_dog
l_dog.eat (meat)
when attached {FISH} l_pet as l_fish
l_fish.eat (plants)
else
io.put_string ("Strange animal how do I feed him???")
end
do
the compiler is complaining with the attached
after when...
because it just happened me to mess up with repeated copy-paste which is what a language tries to help avoiding. In the above case, the l_pet
is written one time, with a N times if/else I'd have to write it as much times as ifs...
An inspect
statement allows for checking if an expression has a specific value, and can be applied to expressions of integral types (such as INTEGER_64
, CHARACTER_32
or NATURAL_8
):
inspect age
when 6 .. 16 then ...
when 18 then ...
when 80, 90 then ...
...
end
For discriminating over object types, conditional instructions are used:
if attached {DOG} pet as dog then
dog.eat (meat)
elseif attached {FISH} pet as fish then
fish.eat (plants)
else
io.put_string ("Strange animal how do I feed him???")
end