When is it okay to use “var” in Scala?

巧了我就是萌 提交于 2020-01-22 13:25:28

问题


I know that Scala has var (for mutable state) but pure functional programming discourages use of any mutable state and rather focuses on using val for everything.

Coming from an imperative world it's hard to let go of mutable state.

My question is when is it okay to use var in your Scala code ? Can all code really be done using just val. If yes, then why does Scala have vars?


回答1:


Here are some reasons for vars in Scala:

  • Scala is a multi-paradigm language, it encourages functional programming, but it leaves the choice to the programmer.
  • Comptibility: Many Java APIs expose mutable variables.
  • Performance: Sometimes using a var gives you the best possible performance.
  • When people say that everything can be done without vars, that is correct in the sense that Scala would still be turing complete without vars. However, it doesn't change anything about the validity of the previous points.



回答2:


Even from a functional programming point of view, you can use vars (or mutable objects) locally, if they don't leave the scope where they are defined.

For instance, consider this (contrived) function, which returns the size of a list:

def dumbSize( lst: List[Int] ): Int = {
   var i = 0
   var rest = lst
   while( rest != Nil ) {
     i += 1
     rest = rest.tail
   }
   i
}

Altough this (ugly) function uses vars, it is still pure (there are no side effects and it will always return the same result for a given argument value).

Another example of "mutable-state-encapsulation", is the actor model, where actor state is often mutable.



来源:https://stackoverflow.com/questions/13097302/when-is-it-okay-to-use-var-in-scala

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