Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin Generics Error in Java

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.

like image 284
M-WaJeEh Avatar asked Jan 11 '18 22:01

M-WaJeEh


2 Answers

Change your ConcreteUseCase as following:

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

For more information visit this link

like image 53
hluhovskyi Avatar answered Sep 19 '22 21:09

hluhovskyi


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.

like image 25
s1m0nw1 Avatar answered Sep 19 '22 21:09

s1m0nw1