Hey, I was messing around with covariance and cont...
# announcements
c
Hey, I was messing around with covariance and contravariance and did not expect this to work. It looks like I created a function which is bivariant. How is that possible as the following code compiles and runs.
Copy code
class Container<in T>(private val t: T) 

open class Noun
open class City: Noun()
class Capital: City()

fun goCity(container: Container<City>) {
    println(container)
}

fun main() {
    goCity(Container(Noun())) // pass in a super type of City, this is what I would expect as it is defined contravariance
    goCity(Container(Capital())) // pass in a sub type of City, would not have expected this as it is defined contravariance
}
m
Copy code
goCity(Container(Capital()))
This creates a
Container<City>
implicitly because it satisfies both: passing in
Capital
as a constructor parameter and the expected type
Container<City>
for
goCity
c
🙇 Thank you