为了账号安全,请及时绑定邮箱和手机立即绑定

从 Kotlin 调用需要 Function 参数的 Java 方法

从 Kotlin 调用需要 Function 参数的 Java 方法

慕森王 2022-07-20 20:47:48
我在将这部分 Java 转换为 Kotlin 时遇到问题:Publishers.map(chain.proceed(request), response -> {            if (request.getCookies().contains("SOME_VALUE")) {                 response.cookie(request.getCookies().get(STATE_COOKIENAME).maxAge(0));            }            return response;        });该map方法的第二个参数(注意Publishers不是集合)采用Function<T,R>. 我尝试了几种解决方案,包括提供一个 lambda:Publishers.map(chain?.proceed(request), {        x: MutableHttpResponse<*>!,        y: MutableHttpResponse<*>! -> print("It worked")    })但这会导致:错误:(32, 38) Kotlin: Unexpected token错误:(33, 38) Kotlin: Unexpected token错误:(31, 27) Kotlin:类型推断失败:fun map(publisher: Publisher!, mapper: Function!): Publisher! 不能应用于 (Publisher>!>?,(MutableHttpResponse<>, MutableHttpResponse<*>) -> Unit)错误:(31, 56) Kotlin: Type mismatch: inferred type is (MutableHttpResponse< >, MutableHttpResponse< >) -> Unit but Function>!, MutableHttpResponse<>?>! 预计并提供一种方法:return Publishers.map(chain?.proceed(request), ::processCookie)private fun processCookie(a: MutableHttpResponse<*>?) {   print("something something something")}这导致:错误:(31, 27) Kotlin:类型推断失败:fun map(publisher: Publisher!, mapper: Function!): Publisher! 不能应用于 (Publisher>!>?,KFunction1<@ParameterName MutableHttpResponse<>?, Unit>)错误:(31, 56) Kotlin: Type mismatch: inferred type is KFunction1<@ParameterName MutableHttpResponse<>?, Unit> but Function>!, MutableHttpResponse<*>?>! 预计对于上下文,我认为在 kotlin中尝试本教程会很有趣。
查看完整描述

1 回答

?
PIPIONE

TA贡献1829条经验 获得超9个赞

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


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

})

whereT和R必须用实际类型替换


查看完整回答
反对 回复 2022-07-20
  • 1 回答
  • 0 关注
  • 183 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信