djondal djondal - 1 month ago 17
Scala Question

How to avoid mutable local variables in Scala?

It is considered a good practice to avoid using mutable variables in Scala.

From "Programming in Scala, 2nd Edition", page 52: "Scala allows you to program in an imperative style, but encourages you to adopt a more functional style" and later "Scala encourages you to lean towards vals, but ultimately reach for the best tool given the job at hand."

How do you make this imperative construct elegant in Scala (focusing on variable count):

var count = 0
val foo = getRequest()
if(foo.isJsonObject){
count = doSomething(foo)
}
if(count>0){
specialCall()
} else{
defaultCall()
}


What construct or pattern do you use to transform your code with an imperative style to a functional style?
Do you make use of the Option class or some other constructs?

Answer

Not sure if you are giving enough context, but what about:

val foo  = getRequest()
val count = if (foo.isJsonObject) doSomething(foo) else 0
if (count > 0) {
  specialCall()
} else {
  defaultCall()
}

Normally, the Scala API in general (collections, Option, Try, Future, etc) and their operations (map, flatMap, filter, fold, etc) allow you to express most imperative constructs quite concisely.

Comments