added lesson 7
This commit is contained in:
25
src/Lesson7/Variance.sc
Normal file
25
src/Lesson7/Variance.sc
Normal file
@@ -0,0 +1,25 @@
|
||||
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
|
||||
Reference in New Issue
Block a user