Let ret: Number
If(someCondition){
<a lot of expensive calculations>
ret = resultOfOperations
} else {
<a lot of other different expensive operations>
ret = resultOfOtherOperations
}
return ret
letret = if some_condition {
<a lot of expensive calculations>
result_of_operations
} else {
<a lot of other different expensive calculations>
result_of_other_operations
};
Now you don’t have to declare it inside the blocks.
To be honest I always disliked variable declaration without value assignment, so to me both options suck. :)
What about
Let ret: Number If (someCondition) { <a lot of expensive calculations> ret = resultOfOperations } else { <a lot of other different expensive operations> ret = resultOfOtherOperations } return ret
You can’t declare ret inside the brackets
let ret = someCondition ? expensiveOperation() : otherOperation()
?
Yeah. That works.
Rust would allow you to
let ret = if some_condition { <a lot of expensive calculations> result_of_operations } else { <a lot of other different expensive calculations> result_of_other_operations };
Now you don’t have to declare it inside the blocks.
Similarly, Perl lets you say
my $ret = do { if (...) { ... } else { ... }};
That’s… Disgusting
It’s the same thing as ternary, just without the
? :
syntax.What’s disgusting about it? The only thing I can think of is the implicit return, which felt a bit icky at first.
Also, as the if expression is an expression, you can call methods on it like so:
if 1 > 2 { 3 } else { 4 }.min(5)
(the above is still an expression, so it could be used, for example, as part of a condition for another if)
Of course, you can write horrible code in any language, but the ability to use blocks where expressions are expected can be great sometimes.
What about you declare (then it gets allocated in stack) it and pass it to a different context for assignment?
Well, I don’t know your use case well enough, but I guess you might have perfect reason for that behavior.
One thing that comes to my mind is the old Try in C#
bool parsedSuccessfully = int.TryParse("123", out int result);
But I guess more popular approach would be to use Error as Values, right?
E.g. something like this
Outcome<Exception, Int> result = int.TotallyNewParse("123");