djondal djondal - 8 months ago 60
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()
count = doSomething(foo)
} else{

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?


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) {
} else {

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.