什么时候应该使用let {},什么时候只是简单的!= null

你会怎样用更多kotlinic的方式编写下面的代码?什么时候应该使用let {},什么时候只是简单的!= null

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

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

回答:

  • 常见共享代码 - 在这种情况下,错误报告和失败结果返回 - 可合并为local function。
  • 导致返回的可空性(在这种情况下,s3data可为空)通常可以用返回的?: elvis operator代替。
  • 当反复输入相同的变量(在这种情况下,访问s3data)时,run块是适当的。如果混淆,请参阅What is a "receiver" in Kotlin?
  • 正如另一个答案中所述,如果/ else块是Kotlin中的表达式。

因此我会发现下面的实现最ideomatic,受本地函数的参数恰当的命名:

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。

回答:

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

}

以上是 什么时候应该使用let {},什么时候只是简单的!= null 的全部内容, 来源链接: utcz.com/qa/258177.html

回到顶部