Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
If statement 是否可以在;如果;科特林的情况?_If Statement_Variables_Kotlin_Optimization - Fatal编程技术网

If statement 是否可以在;如果;科特林的情况?

If statement 是否可以在;如果;科特林的情况?,if-statement,variables,kotlin,optimization,If Statement,Variables,Kotlin,Optimization,我有一行代码: if (x * y * z > maxProduct) maxProduct = x * y * z 但我的问题是,当我想这样使用它时,我必须写两次x*y*z。我知道我可以在if语句之前创建一个变量,如下所示: val product = x * y * z if (product > maxProduct) maxProduct = product (x * y * z).takeIf { it > maxProduct }?.let { maxProdu

我有一行代码:

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

val product = x * y * z
if (product > maxProduct) maxProduct = product
(x * y * z).takeIf { it > maxProduct }?.let { maxProduct = it }

但我不喜欢这样,我必须创建一个临时变量,只用于这个表达式。有什么方法可以改进我的代码吗?

对于您的要求,没有什么好的改进。但是,如果您希望在不创建新变量的情况下使用一些函数样式代码,请使用以下内容:

val product = x * y * z
if (product > maxProduct) maxProduct = product
(x * y * z).takeIf { it > maxProduct }?.let { maxProduct = it }
它的可读性较差,因此我建议使用一个附加变量

maxProduct = maxProduct.coerceAtLeast(x * y * z)

更一般地说(对于没有快捷方式函数的表达式),
.let()
可用于避免使用单独的变量。但当你把它挤在一行上时,我认为它不那么容易阅读:

(x * y * z).let { if (it > maxProduct) maxProduct = it }

当(val时,您可能可以使用
,但最终结果不会更好。我只需要创建val。此外,您可以使用
(x*y*z)。让{…}
(x*y*z)。运行{…}
与(x*y*z){…}
),或者对于您的代码片段,您可以使用
maxProduct=max(maxProduct,x*y*z)
。您可以采用不同的方式,但这样做不会提高性能或可读性…
maxProduct=max(maxProduct,x*y*z)
是最简单的方法,似乎可以满足此问题的要求,但可读性(对我而言)要差得多;-)