How to avoid mutable local variables in Scala?

女生的网名这么多〃 提交于 2019-12-24 01:17:34

问题


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:


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.




回答2:


@ale64bit answer is fine but you can express it shorter

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



回答3:


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.



来源:https://stackoverflow.com/questions/40117982/how-to-avoid-mutable-local-variables-in-scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!