Contravariance in Kotlin

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() // OK!
    val y: Comparator<in T> = AnyComparator() // Compilation error
}

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.

+5
2

, Any kotlin, . Any? ( Any).

T test , Any?. , Comparator<Any>, Comparator<Any?>.

, , T Any:

fun <T: Any> test() {
    //...
}
+10

, ? kotlin, Any Any? . :

    val string1: String = "Sarabjit"

// val newString2 : String = null [this does not work as we cannot assign null to a String which cannot hold a null value

    var checkString: String? = newString1

checkString = null //This works like a charm.
0

Source: https://habr.com/ru/post/1680553/


All Articles