Created
July 3, 2017 16:07
-
-
Save tomaszpolanski/b77e4b5c7d877084d46c1d83d4ee92d5 to your computer and use it in GitHub Desktop.
Covariance vs Contravariance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.tomek | |
abstract class Animal(val size: Int) | |
class Dog(val cuteness: Int): Animal(100) | |
class Spider(val terrorFactor: Int): Animal(1) | |
// Covariance | |
val dogList: List<Dog> = listOf() | |
val animalList: List<Animal> = dogList // Works! | |
val spiderList: List<Spider> = animalList // Compiler error, cannot assign List<Animal> to List<Spider> | |
// Contravariance | |
interface Compare<in T> { | |
fun compare(first: T, second: T): Int | |
} | |
val dogCompare: Compare<Dog> = object: Compare<Dog> { | |
override fun compare(first: Dog, second: Dog): Int { | |
return first.cuteness - second.cuteness | |
} | |
} | |
val animalCompare: Compare<Animal> = dogCompare // Compiler error, cannot assign List<Dog> to List<Animal> | |
val spider: Compare<Spider> = object: Compare<Animal> { // Works! | |
override fun compare(first: Animal, second: Animal): Int { | |
return first.size - second.size | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment