I never understood generics in Java, so this seems to be the case with Kotlin. Consider the following code snippet (this is a far-fetched example):
class AnyComparator: Comparator<Any> {
override fun compare(o1: Any, o2: Any): Int {
TODO("not implemented")
}
}
fun <T> test() {
val x: Comparator<in Double> = AnyComparator()
val y: Comparator<in T> = AnyComparator()
}
Second assignment fails
Type mismatch.
Required: kotlin.Comparator<in T>
Found: AnyComparator
Now, if I understand correctly, the modifier inindicates that it is Tconsumed only by the general type Comparator(it makes it contravariant), so I should be able to assign anyone Comparatorwith an argument of the type Ethat is the base class T. Based on this, I would have to assign AnyComparatorfor both variables xand y, since the type Anyis the base class of each class in Kotlin. It turns out I canβt, and I donβt understand why.