10

Given the following three kotlin classes:

abstract class UseCase<T> {
    fun execute(action: Action<T>) {
    }
}

class ConcreteUseCase : UseCase<List<String>>()

class Action<T>

I am unable to compile following lines in java code:

ConcreteUseCase s = new ConcreteUseCase();
s.execute(new Action<List<String>>());//<<<<<<< compilation error

enter image description here

Error says:

SomeClass<java.util.List<? extends Type>> in Class cannot be applied to SomeClass<java.util.List<Type>>

I am still new to kotlin and this might be something very small but I can't seem to figure it out. I will appreciate any help.

Community
  • 1
  • 1
M-Wajeeh
  • 17,204
  • 10
  • 66
  • 103

2 Answers2

11

Change your ConcreteUseCase as following:

class ConcreteUseCase : UseCase<List<@JvmSuppressWildcards String>>()

For more information visit this link

hluhovskyi
  • 9,556
  • 5
  • 30
  • 42
4

To simply fix the Java code without touching Kotlin:

public static void main(String[] args) {
    ConcreteUseCase s = new ConcreteUseCase();
    Action<List<? extends String>> listAction = new Action<>();
    s.execute(listAction);
}

Otherwise: The List in Kotlin is declared as interface List<out E>, i.e. only a producer of Eand thus your method’s parameter type List<? extends T> has wildcards in Java (Producer extends, Consumer super). You can use MutableList on Kotlin side:

class ConcreteUseCase : 
    UseCase<MutableList<String>>

This one does not use declaration-site variance modifiers (in/out) and you’ll be able to call the method as expected.

It’s also possible to use @JvmSuppressWildcards as explained here.

s1m0nw1
  • 76,759
  • 17
  • 167
  • 196
  • 1
    Thanks for the insight. Loved your answer. I am going to use `@JvmSuppressWildcards` for now. – M-Wajeeh Jan 12 '18 at 00:08
  • Nice alternative. Problem is, seems as if your fix forces the user to specify a *mutable* list, which may be undesired. – Vince Jan 12 '18 at 00:52
  • Not at all. Just used it to make clear what is going on. You can leave List as is, I added an example – s1m0nw1 Jan 12 '18 at 01:10