Currently Kotlin compiler treats all type parameters on Java classes as invariant, which can cause valid code to be rejected. The simplest way to solve this is to translate that Java file to Kotlin and manually add declaration-site variance, which only works if we have full control of the source file and its build system (i.e. We are able to add kotlin stdlib dependency to it). I also know that JEP 300 proposes to add declaration-site variance to Java, but that’s far away from realization. So I wonder if we could modify the Kotlin compiler to allow Java classes to specify declaration-site variance.
Implementation wise, I can think of the following ways:
- Use a class level (or type parameter level, which requires Java 1.8
ElementType.TYPE_PARAMETER) annotation to specify the variance of some of the type parameters. And then read the annotation in Kotlin compiler and let
KotlinTypeMapperknow this so that it knows the
JavaTypeParametershould have such variance. This requires full control of the source file but doesn’t change the build system (The class stays in Java), and modifications to the compiler.
- Process the compiled class file somewhere in the build system (either in the project producing the Jar, or in the consuming side), to add Kotlin metadata to it to specify the variance. This sounds a lot simpler than the above, as it only involves build system changes.
Any thoughts on this?