mardi 9 juin 2020

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

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?

Aucun commentaire:

Enregistrer un commentaire