[英]Kotlin overload on lambdas that return a value VS ones that don't. Java, Groovy works, but Kotlin doesn't
對 Kotlin 非常陌生,並試圖讓我的一些 API 在 Kotlin 中工作,而無需過多更改 API。
我有一個方法,我們稱它為接收validation
function 的client
Validation
有兩種變體。 一個只假設進行驗證,另一個也可以返回一個值。 為了簡化用戶體驗,在 Java 中,我公開了該方法的兩個變體。 它按預期工作,因為我相信 Java 可以區分void
和Object
(<R>)。
當我在 Kotlin 中使用我的代碼時,它不能區分兩者,我需要提供一個顯式轉換。
為了從等式中刪除 Java,我嘗試使用函數接口復制 Kotlin 中的情況:
fun interface KotlinValidator {
fun validate()
}
fun interface KotlinValidatorWithReturn {
fun validateAndReturn(): Any
}
fun client(validator: KotlinValidator) {
println("validator NO return")
validator.validate()
}
fun client(validatorAndReturn: KotlinValidatorWithReturn): Any {
println("validator WITH return")
return validatorAndReturn.validateAndReturn()
}
fun test() {
val fromValidator = client {
100
}
val fromValidatorForced = client(KotlinValidatorWithReturn {
100
})
client {
}
}
它打印
validator NO return
validator WITH return
validator NO return
根據我的谷歌搜索,如果沒有明確的演員表,似乎不可能讓它工作。 但是我希望我錯了,因為 Groovy 和 Java 讓我來做。
為了提供更多上下文,我正在嘗試使WebTau HTTP 模塊與 Kotlin 很好地協同工作。
在 Java 和 Groovy 版本中我可以這樣做:
int id = http.post("/customers", customerPayload, ((header, body) -> {
return body.get("id");
}));
http.put("/customers/" + id, changedCustomerPayload, ((header, body) -> {
body.get("firstName").should(equal("FN"));
body.get("lastName").should(equal(changedLastName));
}));
在 Groovy:
def id = http.post("/customers", customerPayload) {
body.id
}
但是在 Kotlin 中:
val id: Int = http.post("/customers", customerPayload, HttpResponseValidatorWithReturn { _, body ->
body.get("id")
})
我提出這個例子的原因是目前我不願意更改 API 和重命名函數以區分返回值和不返回值的函數。
主要問題是在 Kotlin 中,一切都會返回——它們可能只返回Unit
。 沒有void
。
另一方面,這可能意味着不需要區分這些類型,你可以只使用“with return”版本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.