【问题标题】:From Kotlin call Java method requiring Function parameter从 Kotlin 调用需要 Function 参数的 Java 方法
【发布时间】:2019-07-28 01:38:44
【问题描述】:

我在将这部分 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: Type inference failed: fun map(publisher: Publisher!, mapper: Function!): Publisher! 不能应用于 (Publisher>!>?,(MutableHttpResponse, MutableHttpResponse) -> 单位)

Error:(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: Type inference failed: fun map(publisher: Publisher!, mapper: Function!): Publisher! 不能应用于 (Publisher>!>?,KFunction1?, Unit>)

Error:(31, 56) Kotlin: Type mismatch: inferred type is KFunction1?, Unit> but Function>!, MutableHttpResponse?>!预料之中

对于上下文,我认为在 kotlin 中尝试 this tutorial 会很有趣。

【问题讨论】:

  • 第三种解决方案是将代码保留为 Java。

标签: java kotlin interop


【解决方案1】:

您没有在 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&lt;T,R&gt;。您可能需要明确使用名称,例如

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

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

【讨论】:

  • 谢谢尤金,我会试试看的 :)
  • 第三个建议(也为 Java Function 类型提供类型参数)已编译。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-17
  • 1970-01-01
  • 2023-02-15
  • 2019-01-02
  • 1970-01-01
相关资源
最近更新 更多