Is it possible to declare a variable inside of the "if" condition in Kotlin?

Viewed 3723

I have this line of code:

if (x * y * z > maxProduct) maxProduct = x * y * z

But my problem is that I have to write x * y * z two times when I want to use it like this. I know I could create a variable before the if statement, like this:

val product = x * y * z
if (product > maxProduct) maxProduct = product

But I don't like that I have to create a temporary variable that's used just for this expression. Is there a way to improve my code?

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

or

maxProduct = max(maxProduct, x * y * z)

More generally (for expressions that don't have a shortcut function), .let() can be used to avoid the separate variable. But when you squeeze it on one line, in my opinion it's not as easy to read:

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

There is no good improvement for your requirement. But if you want some functional style code without creating a new variable use something like this:

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

It is less readable, so I would suggest to stick with an additional variable.

Related