亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從 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:類型推斷失?。篺un 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:類型推斷失?。篺un 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 關注
  • 266 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號