Constrained genericity: Difference between revisions

Added Kotlin
(Added Sidef)
(Added Kotlin)
Line 700:
<lang java5>test.<EatableClass>bar();</lang>
The <code>foo</code> method from before can figure out <code>T</code> from its parameter, but this <code>bar</code> method needs to be told what T is.
 
=={{header|Kotlin}}==
In the following program we define an interface, Eatable, and two classes - Cheese and Meat - which implement it and must therefore implement its eat() method because the interface itself does not provide a default implementation.
 
We then define a generic class, FoodBox, whose type parameter, T, is constrained to an Eatable type and instantiate it using both the Cheese and Meat types:
<lang scala>// version 1.0.6
 
interface Eatable {
fun eat()
}
 
class Cheese(val name: String) : Eatable {
override fun eat() {
println("Eating $name")
}
 
override fun toString() = name
}
 
class Meat(val name: String) : Eatable {
override fun eat() {
println("Eating $name")
}
 
override fun toString() = name
}
 
class FoodBox<T: Eatable> {
private val foodList = mutableListOf<T>()
 
fun add(food: T) {
foodList.add(food)
}
 
override fun toString() = foodList.toString()
}
 
fun main(args: Array<String>) {
val cheddar = Cheese("cheddar")
val feta = Cheese("feta")
val cheeseBox = FoodBox<Cheese>()
cheeseBox.add(cheddar)
cheeseBox.add(feta)
println("CheeseBox contains : $cheeseBox")
 
val beef = Meat("beef")
val ham = Meat("ham")
val meatBox = FoodBox<Meat>()
meatBox.add(beef)
meatBox.add(ham)
println("MeatBox contains : $meatBox")
 
cheddar.eat()
beef.eat()
println("Full now!")
}</lang>
 
{{out}}
<pre>
CheeseBox contains : [cheddar, feta]
MeatBox contains : [beef, ham]
Eating cheddar
Eating beef
Full now!
</pre>
 
=={{header|Morfa}}==
9,483

edits