3

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?

1
  • The pattern to use here is expression orientation. So normally we don't think of control-flow operations (if, try, match) as expressions that evaluate to result values but in Scala and other similar languages they are. Commented Oct 18, 2016 at 22:18

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I like this as it is elegant and concise.
2

@ale64bit answer is fine but you can express it shorter

val foo  = getRequest()
if (foo.isJsonObject && doSomething(foo)>0)  
   specialCall()
else 
   defaultCall()

Comments

1

There are many ways to do this.

val count = Try(getRequest).filter(_.isJsonObject).map(doSomething).getOrElse(0)

if (count > 0) {
  specialCall()
} else {
  defaultCall()
}

You can even avoid the if-else condition (by pattern matching), but that may reduce the readability of the code.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.