Direct Affectation on If Conditions

Greetings,

Can you make it possible to introduce affectations in if-clauses’ conditions, in such a way that if the condition is filled (for instance), its result is affected to the “condition-variable”, so that variable could be used later on inside the if block ?

This screenshot shows what’s actually done :

Screenshot from 2022-07-26 03-53-33

Here’s my proposition :
if (val s = test_condition) {
//something I’m gonna do with s
}

Another example is when (for instance) I wanna know if the result of the multiplication of 2 numbers is odd, then I do an action A with that result. Instead of creating a variable outside the if block and then using it later on, what if we affect the result to the variable at the if-condition level ?

Regards.

The problem with this approach is that you probably need another value inside if than you used as a condition. if (val s = test_condition) doesn’t make too much sense, because you know that s is always true. And if we have to declare the value and the condition separately, so something like:

return if (val token = ArakaTokenStream.readToken(); !token.isNullOrBlank())

Then it is basically the same as your original code, only less readable.

One thing you can do is to use scope functions, for example:

ArakaTokenStream.readToken().takeIf { !it.isNullOrBlank() }?.let { token -> 
    ...
}

Although, I’m personally not a huge fun of this. Assignment and if seems easier to read and reason about.

I kinda agree with you, and I think the first solution would be less verbose and efficient.

Thanks, @broot .