Search code examples
scalaapache-sparkif-statementscopevar

How to update a var inside if-statement in Scala Spark?


I have a tracking variable that is supposed to denote whether we've arrived at a certain branch in a nested if-else statement. Here's a simplified example

var varChanged = false
if(true) {
  var varChanged = true
}

varChanged //still returns false

I would like to update the value of varChanged within the if statement. How should I go about doing this? I can't use the if statement as an expression like var varChanged = if(..).. because I'm using it as an expression for another val and varChanged is just a tracking variable that I need.


Solution

  • Remove the inner var keyword

    var varChanged = false
    if(true) {
      varChanged = true
    }
    

    You were shadowing the outer varChanged by declaring it again in the inner scope.

    You should really avoid using vars as much as possible.