Contravariance in Kotlin
It can be seem strange but Any
is not the superclass of all kotlin classes but only of not nullable classes. The real superclass of all Kotlin classes is Any?
(it is also a superclass of Any
).
The generic type T
in your test
function has no upper bound so it can be a nullable object Any?
. The error is because you can't a Comparator<Any>
when you need a Comparator<Any?>
.
So you can fix your example defining the T
upper bound as Any
:
fun <T: Any> test() {
//...
}