Contravariant (in) parameter bound


#1

In Kotlin, I can’t do this (the in bound is not valid):

fun <T: in MyClass> myfunc(creator: (Int) -> Array<T>): Array<T> = creator(42)

I know this isn’t possible in Java either; but this limitation is rather artificial. There is no fundamental limitation here, and this is purely a type-checking/inference issue anyway.

Would it be possible to consider adding this to the language?

Note that for proper collections, it is possible to do this, but not for array (which are always treated covariantly):

fun <A: MutableList<in MyClass>> myfunc(creator: (Int) -> A): A = creator(42)

#2

We were able to specify Array as an upper bound of generic type parameter (like in fun <T, A: Array<in T>>(creator: (Int) -> A) before, but we had to restrict this because some external tools did not support the bytecode generated.

See https://youtrack.jetbrains.com/issue/KT-9189 for details.


#3

Aha, interesting. Why not make it a warning though?

If it must be an error, would an annotation to disable it be in the cards?