Constrained genericity: Difference between revisions

Added Wren
(Rename Perl 6 -> Raku, alphabetize, minor clean-up)
(Added Wren)
Line 1,597:
<lang swift>func foo<T: Eatable>(x: T) { }
// although in this case this is no more useful than just "func foo(x: Eatable)"</lang>
 
=={{header|Wren}}==
Wren is dynamically typed and so any constraint on class instantiation can only be checked at run time.
<lang ecmascript>// abstract class
class Eatable {
eat() { /* override in child class */ }
}
 
class FoodBox {
construct new(contents) {
if (contents.any { |e| !(e is Eatable) }) {
Fiber.abort("All FoodBox elements must be eatable.")
}
_contents = contents
}
 
contents { _contents }
}
 
// Inherits from Eatable and overrides eat() method.
class Pie is Eatable {
construct new(filling) { _filling = filling }
 
eat() { System.print("%(_filling) pie, yum!") }
}
 
// Not an Eatable.
class Bicycle {
construct new() {}
}
 
var items = [Pie.new("Apple"), Pie.new("Gooseberry")]
var fb = FoodBox.new(items)
fb.contents.each { |item| item.eat() }
System.print()
items.add(Bicycle.new())
fb = FoodBox.new(items) // throws an error because Bicycle not eatable</lang>
 
{{out}}
<pre>
Apple pie, yum!
Gooseberry pie, yum!
 
All FoodBox elements must be eatable.
[./constrained_genericity line 9] in init new(_)
[./constrained_genericity line 12] in
[./constrained_genericity line 34] in (script)
</pre>
 
=={{header|zkl}}==
9,476

edits