Constrained genericity: Difference between revisions

mNo edit summary
Line 680:
 
=={{header|Julia}}==
{{works with|Julia|0.6}}
Julia allows user defined types with inheritance. Misuse of a type generally produces a compile time error message.
<lang julia>abstract type Edible end
eat(::Edible) = "Yum!"
abstract type Edible <: AbstractString end
 
mutable struct FoodBox{T<:Edible}
food::EdibleVector{T}
function FoodBox(provisions)
this = new()
this.food = provisions
this
end
end
 
mutable struct Carrot <: Edible
variety::StringAbstractString
function Carrot(v)
this = new()
this.variety = v
this
end
end
 
mutable struct CarBrick
makevolume::StringFloat64
model::String
year::Integer
function Car(mak, mod, yr)
this = new()
this.make = mak
this.model = mod
this.year = yr
this
end
end
 
carrotc = Carrot("Baby")
function eat(food::Edible)
b = Brick(125.0)
println("Yum")
eat(c)
end
eat(b)</lang>
 
carrot = Carrot("Baby")
{{out}}
car = Car("Honda", "Civic", 1975)
<pre>MethodError: no method matching eat(::Brick)
foodbox1 = FoodBox(carrot)
Closest candidates are:
foodbox2 = FoodBox(car)
eat(!Matched::Edible) at console:2</pre>
</lang>
{{output}}
ERROR: LoadError: MethodError: Cannot `convert` an object of type Car to an object of type Edible
 
=={{header|Kotlin}}==
Anonymous user