[英]Kotlin Lambda function as a parameter
I am new to Kotlin and have difficulty understand the code below我是 Kotlin 的新手,很难理解下面的代码
private fun <T> catchAsyncExceptions(f: () -> CompletableFuture<T>) =
try {
f().get()
} catch (e: ExecutionException) {
throw e.cause!!
}
So this function is called catchAsyncExceptions
, its input parameter is a function called f
which is () -> CompletableFuture<T>
So I would think that you use it by所以这个 function 被称为catchAsyncExceptions
,它的输入参数是一个 function 称为f
是() -> CompletableFuture<T>
所以我认为你使用它
catchAsyncExceptions(someFunctionThatTakesNoArgumentAndReturnsCompletableFuture)
However I see the usage is但是我看到用法是
override fun getUserInfo(userId: String) =
catchAsyncExceptions {
membersClient.getUserLocation(
GetUserLocationRequest(userId)
)
.thenApply { response ->
val (success, error) = parseSuccessAndError<GetUserLocationResponseResult.Success>(response.result!!)
error?.let {
UserInfoResponse(
error = error.code
)
)
} ?: run {
UserInfoResponse(
data = UserInfoResponseDto(
location = success?.success?.location.toString(),
)
)
}
}
}
Note that注意
membersClient.getUserLocation(
GetUserLocationRequest(userId)
)
returns CompletableFuture
type返回CompletableFuture
类型
I am especially confused why it was a curly bracket rather than a bracket我特别困惑为什么它是花括号而不是括号
catchAsyncExceptions {
...
}
In Kotlin, when you have a lambda function as a parameter, the brackets are completely optional.在 Kotlin 中,当你有一个 lambda function 作为参数时,括号是完全可选的。 You can rewrite the implementation as:您可以将实现重写为:
catchAsyncExceptions({
membersClient.getUserLocation(
GetUserLocationRequest(userId)
)
.thenApply({ response ->
val (success, error) = parseSuccessAndError<GetUserLocationResponseResult.Success>(response.result!!)
error?.let({
UserInfoResponse(
error = error.code
)
)
}) ?: run({
UserInfoResponse(
data = UserInfoResponseDto(
location = success?.success?.location.toString(),
)
)
})
})
})
and this is a perfectly working code.这是一个完美的工作代码。 For simplicity, the brackets are omitted to make the code more readable.为简单起见,省略了括号以使代码更具可读性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.