如何避免Scala中的可变局部变量? [英] How to avoid mutable local variables in Scala?

查看:65
本文介绍了如何避免Scala中的可变局部变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最好避免在Scala中使用可变变量.

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

摘自"Scala编程,第二版",第52页:"Scala允许您以命令式风格进行编程,但鼓励您采用更具功能性的风格",后来又"Scala鼓励您倾向于val,但最终可以根据手头的工作找到最好的工具."

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."

您如何在Scala中使此命令结构优雅(关注变量 count ):

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()
}

您使用什么构造或模式将命令式样式的代码转换为功能样式? 您是否使用Option类或其他一些构造?

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

通常,一般来说,Scala API(集合,OptionTryFuture等)及其操作(mapflatMapfilterfold等)都允许您可以非常简洁地表达最必要的结构.

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.

这篇关于如何避免Scala中的可变局部变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆