Is there a way to prevent upcasting generic types ...
# announcements
Is there a way to prevent upcasting generic types of functions when calling them with different argument types? Say I write the following function as a test util:
Copy code
 * Asserts that two objects of type [T] are equal.
infix fun <T> T.shouldBe(that: T) {
    Assertions.assertEquals(that, this)
So that I can easily write shouldBe value
, this works great. But when I supply two values of different types
"string" shouldBe 5
, the compiler doesn't complain. It infers the generic type to be
. While valid behaviour, it's not what I want to happen. Is there a way I can tell Kotlin to not upcast the generic type if the argument type is not assignable to the receiver type?
Untested, but in theory you should be able to create bounds in both directions:
<A : B, B : A>
Causes a cyclic upperbounds error ^. Don’t think this is something kotlin supports. You would need to create static functions for each kind you want to support, as the generic parameter is always going to try to resolve the argument to some super type (kind of the point of having them).
The annotation in this issue is what you're looking for I believe