From Kotlin call Java method requiring Function parameter

时间:2019-03-06 11:39:58

标签: java kotlin interop

I am having problems converting this chunk of Java to Kotlin:

Publishers.map(chain.proceed(request), response -> {
            if (request.getCookies().contains("SOME_VALUE")) { 
                response.cookie(request.getCookies().get(STATE_COOKIENAME).maxAge(0));
            }
            return response;
        });

The second parameter of the map method (note Publishers is not a collection) takes Function<T,R>. I have tried several solutions, including providing a lambda thus:

Publishers.map(chain?.proceed(request), {
        x: MutableHttpResponse<*>!,
        y: MutableHttpResponse<*>! -> print("It worked")
    })

but that results in:

Error:(32, 38) Kotlin: Unexpected token

Error:(33, 38) Kotlin: Unexpected token

Error:(31, 27) Kotlin: Type inference failed: fun map(publisher: Publisher!, mapper: Function!): Publisher! cannot be applied to (Publisher>!>?,(MutableHttpResponse<>, MutableHttpResponse<*>) -> Unit)

Error:(31, 56) Kotlin: Type mismatch: inferred type is (MutableHttpResponse<>, MutableHttpResponse<>) -> Unit but Function>!, MutableHttpResponse<>?>! was expected

and providing a method:

return Publishers.map(chain?.proceed(request), ::processCookie)

private fun processCookie(a: MutableHttpResponse<*>?) {
   print("something something something")
}

which results in:

Error:(31, 27) Kotlin: Type inference failed: fun map(publisher: Publisher!, mapper: Function!): Publisher! cannot be applied to (Publisher>!>?,KFunction1<@ParameterName MutableHttpResponse<>?, Unit>)

Error:(31, 56) Kotlin: Type mismatch: inferred type is KFunction1<@ParameterName MutableHttpResponse<>?, Unit> but Function>!, MutableHttpResponse<*>?>! was expected

For context I thought it would be fun to attempt this tutorial in kotlin.

1 个答案:

答案 0 :(得分:2)

您未在lambda中指定返回类型,这是Kotlin推断的。最后一个示例不起作用,因为该函数的返回类型为Unit,在Java中为void。我会尝试以下方法:

return Publishers.map(chain?.proceed(request), ::processCookie)

private fun processCookie(a: MutableHttpResponse<*>?) : MutableHttpResponse<*>? {
   print("something something something")
   return a
}

如果您写的话也可能有用

return Publishers.map(chain?.proceed(request)) { 
  print("something something something")
  it
}

我们在这里使用Kotlin中Lambda的默认参数名称-it。 Kotlin编译器将为您推断类型。 Kotlin中还允许将函数的最后一个lambda参数移到方括号之外。

Java功能接口的最后一件事,例如Function<T,R>。您可能需要明确使用该名称,例如

return Publishers.map(chain?.proceed(request), Function<T,R> { 
  print("something something something")
  it
})

其中TR必须替换为实际类型