Suppose have 3 numbers:
val x = 10
val y = 5
val z = 14
and we want to do some logic like:
if (x + y > z) {
println(x + y)
} else if (x + y < z) {
println(-1)
} else {
println(0)
}
If our "z + y" operation is expensive we must calculate it exactly once:
val sum = x + y
if (sum > z) {
println(sum)
} else if (sum < z) {
println(-1)
} else {
println(0)
}
but I want more functional way like:
if (x + y > z) => sum { //This is will not compile :)
println(sum)
} else if (sum < z) {
println(-1)
} else {
println(0)
}
Something without needing another statement to store the result. Something that I can compound with another function, like:
if(x + y > z) sum {
if(sum + 10 > 100) other_sum {
... etc
PS. Match does not help:
x + y match {
case result if result > z => println(result)
case result if result < z => println(-1)
case _ => println(0)
}
or
val sum = x + y
sum match {
case _ if sum > z => println(sum)
case _ if sum < z => println(-1)
case _ => println(0)
}
It still looks bad.
Calculating the sum in a temporary variable is no less functional than your other solutions. And if the calculation is complex then you can use the name of the temporary variable to describe the result and make the code more readable.
If you want to compose it with other code then you can easily wrap it in a function.
Here is another way to avoid the temporary variable, though it is not necessarily any better than the others.
((sum: Int) =>
if (sum > z) {
println(sum)
} else if (sum < z) {
println(-1)
} else {
println(0)
}) (x + y)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With