2

您将如何以更 kotlinic 的方式编写以下代码?

var returnValue = ...
val s3data = presignedUrl.body()
if (s3data != null) {
    val uploadImage = api.uploadImage(s3data.bucketUrl, s3data.awsAccessKeyId, s3data.policy, s3data.key, s3data.signature, body).execute()
    if (!uploadImage.isSuccessful) {
        crashReporterService.sendIssue("Failed uploading file", "Failed uploading file ${uploadImage.raw()}")
        returnValue = Result.FAILURE
    } else {
        returnValue = Result.SUCCESS
    }
} else {
    crashReporterService.sendIssue("Failed uploading image", "Error - ${presignedUrl.raw()}")
    returnValue = Result.FAILURE
}

return returnValue

我可以使用let,但我觉得它使代码更难理解

4

2 回答 2

6
  • 公共共享代码——在这种情况下,错误报告和返回失败结果——可以合并到一个本地函数中。
  • 导致返回的可空性(在这种情况下,s3data可以为空)通常可以用返回的?: elvis 运算符替换。
  • 当一遍又一遍地输入相同的变量时(在这种情况下,访问s3data),一个run块是合适的。如果感到困惑,请参阅Kotlin 中的“接收器”是什么?
  • 如另一个答案中所述,if/else 块是 Kotlin 中的表达式。

因此,我会发现以下实现最符合概念,但要正确命名本地函数的参数:

fun foo() {
    fun failure(p0: String, p1: String) = crashReporterService.sendIssue(p0, p1).let { Result.FAILURE }
    val s3data = presignedUrl.body() ?: return failure("Failed uploading image", "Error - ${presignedUrl.raw()}")
    val uploadImage = s3data.run { api.uploadImage(bucketUrl, awsAccessKeyId, policy, key, signature, body).execute() }

    return if (uploadImage.isSuccessful) {
        Result.SUCCESS
    } else {
        failure("Failed uploading file", "Failed uploading file ${uploadImage.raw()}")
    }
}

您的问题与代码审查有关,因此您可能也很高兴知道有一个专门的 Stack Exchange 网络。不过,请务必先阅读适用于 Stack Overflow 用户的代码审查指南

于 2017-12-03T07:44:47.790 回答
4

if/else是 Kotlin 中的一个表达式,因此以下内容肯定更 Kotlinesque:

val s3data = presignedUrl.body()
return if (s3data != null) {
    val uploadImage = api.uploadImage(s3data.bucketUrl, s3data.awsAccessKeyId, s3data.policy, s3data.key, s3data.signature, body).execute()
    if (!uploadImage.isSuccessful) {
        crashReporterService.sendIssue("Failed uploading file", "Failed uploading file ${uploadImage.raw()}")
        Result.FAILURE
    } else {
        Result.SUCCESS
    }
} else {
    crashReporterService.sendIssue("Failed uploading image", "Error - ${presignedUrl.raw()}")
    Result.FAILURE
}
于 2017-12-02T20:24:11.580 回答