Suppose I have this piece of code in Scala (or other functional programming language):
val nums = Seq(1, 2, 3, 4, 5)
nums.map(n => {
if (n % 2 == 0) {
n * 2 // double the number if it's an even number
}
val a = heavyComputation()
if (a) {
log(a)
n * 3 // triple the number if a is true
}
n
})
this will always return the original list which is not what I want. I know this can fix the issue:
nums.map(n => {
if (n % 2 == 0) {
n * 2
} else {
val a = heavyComputation()
if (a) {
log(a)
n * 3
} else {
n
}
}
})
but I have to nest some code inside the else
. This already makes the code a bit messy. Now what if I have a few more if
checks, I have to nest them again which makes the code not readable.
Why can't I just do return n * 2
in Scala (Or I suppose in any functional style code)?