您如何以更科学的方式编写以下代码?
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,但我觉得它使代码更难理解
答案 0 :(得分:6)
s3data
可以为空)通常可以替换为返回?: elvis operator。s3data
),run
块是合适的。如果感到困惑,请参阅What is a "receiver" in 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()}")
}
}
您的问题接近于代码审核,因此您可能也很高兴知道dedicated Stack Exchange network just for that.之前请先阅读A guide to Code Review for Stack Overflow users。
答案 1 :(得分:4)
if
/else
is an expression in 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
}