Constrained genericity: Difference between revisions

Content added Content deleted
m (removed omit from phix)
No edit summary
Line 190: Line 190:
eatable food)."
eatable food)."
(apply 'make-food-box 'eatable array-args))</lang>
(apply 'make-food-box 'eatable array-args))</lang>

=={{header|Crystal}}==
Similar to Ruby version, but shows error at compile-time.
<lang ruby>class Apple
def eat
end
end

class Carrot
def eat
end
end

class FoodBox(T)
def initialize(@data : Array(T))
{% if T.union? %}
{% raise "All items should be eatable" unless T.union_types.all? &.has_method?(:eat) %}
{% else %}
{% raise "Items should be eatable" unless T.has_method?(:eat) %}
{% end %}
end
end

FoodBox.new([Apple.new, Apple.new])
FoodBox.new([Apple.new, Carrot.new])
FoodBox.new([Apple.new, Carrot.new, 123])</lang>

{{out}}
<pre>
Error in line 23: All items should be eatable
</pre>


=={{header|D}}==
=={{header|D}}==