Kotlin Lambda作为参数的功能
我是Kotlin的新手,很难理解下面的代码
private fun <T> catchAsyncExceptions(f: () -> CompletableFuture<T>) =
try {
f().get()
} catch (e: ExecutionException) {
throw e.cause!!
}
,因此该功能称为Catchasyncexceptions
,其输入参数是一个称为f
的函数,它是>() - &gt ;完整的future&lt; t&gt;
因此,我认为您使用它,
catchAsyncExceptions(someFunctionThatTakesNoArgumentAndReturnsCompletableFuture)
但是我看到用法是
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(),
)
)
}
}
}
指
membersClient.getUserLocation(
GetUserLocationRequest(userId)
)
返回pountableFuture
类型
我特别困惑为什么它是卷发括号而不是括号
catchAsyncExceptions {
...
}
I am new to Kotlin and have difficulty understand the code below
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
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
I am especially confused why it was a curly bracket rather than a bracket
catchAsyncExceptions {
...
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在Kotlin中,当您具有lambda函数作为参数时,括号是完全可选的。您可以将实现重写为:
这是一个完美工作的代码。为简单起见,省略括号以使代码更可读。
In Kotlin, when you have a lambda function as a parameter, the brackets are completely optional. You can rewrite the implementation as:
and this is a perfectly working code. For simplicity, the brackets are omitted to make the code more readable.