是否可以在 Kotlin 中的“if”条件内声明变量?

Dj *_*shi 7 variables optimization if-statement kotlin

我有这行代码:

if (x * y * z > maxProduct) maxProduct = x * y * z
Run Code Online (Sandbox Code Playgroud)

但我的问题是,当我想像这样使用它时,我必须写x * y * z两次。我知道我可以在语句之前创建一个变量if,如下所示:

val product = x * y * z
if (product > maxProduct) maxProduct = product
Run Code Online (Sandbox Code Playgroud)

但我不喜欢必须创建一个仅用于此表达式的临时变量。有没有办法改进我的代码?

Ten*_*r04 8

maxProduct = maxProduct.coerceAtLeast(x * y * z)
Run Code Online (Sandbox Code Playgroud)

或者

maxProduct = max(maxProduct, x * y * z)
Run Code Online (Sandbox Code Playgroud)

更一般地(对于没有快捷函数的表达式),.let()可以用来避免单独的变量。但是当你把它压缩成一行时,我认为它并不那么容易阅读:

(x * y * z).let { if (it > maxProduct) maxProduct = it }
Run Code Online (Sandbox Code Playgroud)


Ser*_*gey 6

对于你的要求没有什么好的改进。但是,如果您想要一些函数式代码而不创建新变量,请使用如下所示:

(x * y * z).takeIf { it > maxProduct }?.let { maxProduct = it }
Run Code Online (Sandbox Code Playgroud)

它的可读性较差,因此我建议坚持使用附加变量。

  • 似乎满足这个问题的要求,但可读性差很多(对我来说);-) (5认同)