简体   繁体   中英

Kotlin vs. Java: Calling function with lambda parameter

I am having this function defined in a kotlin file

fun loadSubmissions(projectId: Long?, completion: (List<Submission>, Exception) -> Unit) { ... }

And want to call it from Java like this

loadSubmissions(project.getProjectId(), (submissions, e) ->
    {
        updateSubmissions(submissions);
        return null;
    });

with

void updateSubmissions(List<Submission> submissionList)
{ .. }

But it gives me

Error:(226, 35) error: incompatible types: List<CAP#1> cannot be 
converted to List<Submission>
where CAP#1 is a fresh type-variable:
CAP#1 extends Submission from capture of ? extends Submission

As I realize the parameter of the lambda function seems to be List<CAP#> instead of the expected and defined List<Submission>

If i convert the class to java, i can easily call that function with the lambda callback.

What am I doing wrong

You have not disclosed the type of variable submissions , but the error message appears to indicate that it is List<? extends Submission> List<? extends Submission> . This is a different type from List<Submission> , and references of the former type are not assignable to variables of the latter type (though the other way around is ok).

That presents at least two problems for you:

  • the lambda itself is not type-correct where it invokes updateSubmissions() , and
  • the lambda's type, which comprises its parameter types, is incompatible with the type of the second parameter of loadSubmissions() .

To fix this, you need either to broaden the parameter types of those two methods or to narrow the type of variable submissions .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM