-3

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)?

1 Answers1

2

Here's one way to adjust the posted code.

nums.map(n => {
  lazy val hc: Boolean = heavyComputation()
 
  if (n % 2 == 0) n * 2           //hc never evaluated  
  else if (hc)   {log(hc); n * 3} //hc is evaluated
  else            n
})
jwvh
  • 50,871
  • 7
  • 38
  • 64