Kotlin Lambda 函数作为参数

Kotlin Lambda function as a parameter

我是 Kotlin 新手,看不懂下面的代码

private fun <T> catchAsyncExceptions(f: () -> CompletableFuture<T>) =
    try {
        f().get()
    } catch (e: ExecutionException) {
        throw e.cause!!
    }

所以这个函数叫做catchAsyncExceptions,它的输入参数是一个叫做f的函数也就是() -> CompletableFuture<T> 所以我认为你使用它

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)
        )

returns CompletableFuture 类型

我特别困惑为什么它是花括号而不是方括号

catchAsyncExceptions {
...
}

在 Kotlin 中,当您将 lambda 函数作为参数时,括号是完全可选的。您可以将实现重写为:

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(),
                    )
                )
            })
        })
})

这是一个完美的工作代码。为简单起见,省略了括号以使代码更具可读性。