Files
FunProg-Scala/src/Lesson7/Variance.sc
2025-04-15 15:07:26 +02:00

25 lines
708 B
Scala

class Animal(val name: String, val kind: String)
class Cat(name: String) extends Animal(name, "Cat")
class Dog(name: String) extends Animal(name, "Dog")
val anim1: Animal = new Animal("Booboo", "Baboon")
val cat1 = new Cat("Miaou")
// Standard polymorphism
val anim2: Animal = cat1
val dog1: Dog = new Dog("Choucroute")
val anim3: Animal = dog1
class Container[+A](val elems: List[A]) {
def get(i: Int): A = elems(i)
def put[B >: A](elem: B) = new Container(elem::elems)
}
val animalCollection = new Container[Animal](Nil).put(anim1)
val catCollection = new Container[Cat](Nil).put(cat1).put(new Cat("Garfield"))
animalCollection.put(cat1)
val animalCollection2: Container[Animal] = catCollection