RosettaCodeData/Task/Constrained-genericity/Pluto/constrained-genericity.pluto
2026-04-30 12:34:36 -04:00

36 lines
888 B
Text

-- Abstract class.
class eatable
function eat() end -- override in child class
end
class foodbox extends eatable
private contents
function __construct(contents)
if !contents:checkall(|c| -> c instanceof eatable) then
error("All foodbox elements must be eatable.")
end
self.contents = contents
end
function getContents() return self.contents end
end
-- Inherits from eatable and overrides eat() method.
class pie extends eatable
function __construct(private filling) end
function eat()
print($"{self.filling} pie, yum!")
end
end
-- Not an eatable
class bicycle end
local items = {new pie("Apple"), new pie("Gooseberry")}
local fb = new foodbox(items)
fb:getContents():foreach(|item| -> item:eat())
print()
items:insert(new bicycle())
fb = new foodbox(items) -- throws an error because bicycle not eatable