Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding Kotlin method with generic parameter in java - method clash

My team is migrating to Kotlin for our Android app, but we still have lots of legacy java code, this causes weird code issues sometimes. This is one of those strange cases.

I have a Kotlin class, call it MyInterface:

interface MyInterface {
    fun onMyObjectList(myObjectList: List<MyObject>)
}

I need to implement this interface in an Activity, written in Java:

class MyActivity implements MyInterface {
...
}

Here's how I implement the overridden method in Java:

@Override
public void onMyObjectList(@NotNull List<MyObject> objectList) {

}

I do want to get a List<MyObject> as a parameter, but the IDE throws an error

onMyObjectList(List<MyObject> objectList) in MyActivity clashes with onMyObjectList(List<? extends MyObject> objectList) in MyInterface. Both methods have the same erasure, yet neither overrides the other

I can't use a List<? extends MyObject> as a parameter as I'm passing it further on to a method that expects a List<MyObject>. How can I configure my Kotlin interface so that it actually uses List<MyObject> instead of List<? extends MyObject> when overridden in Java?

like image 889
Anton Cherkashyn Avatar asked Nov 08 '22 08:11

Anton Cherkashyn


1 Answers

If any of the methods do change the list or reasonably could, using MutableList is indeed the correct solution.

But otherwise, if you are planning to migrate to Kotlin eventually and can't change the other method to take List<? extends MyObject> at this time, I would just prefer to use

@Override
public void onMyObjectList(@NotNull List<? extends MyObject> objectList) {

}

and cast to List<MyObject> before passing to the legacy method. This is 1) a safe cast if you don't mutate the list and 2) a complete non-op at runtime (so it won't affect performance).

like image 129
Alexey Romanov Avatar answered Nov 14 '22 22:11

Alexey Romanov