正如标题所示,只是出于好奇:如果变量被这样声明和实例化,是否存在任何性能或内存分配差异:
class someClass
def showBoard(typeIs: String){
if (typeIs == "animals"){
val dir: File = new File("animals/");
val blah1= ...;
val blah3 = ...;
}
else if (typeIs == "sports"){
//same variables
}
//same for other categories
而不是这个:
class someClass
var dir: File = null
var blah = null
var blah2 = null
def showBoard(typeIs: String){
if (typeIs == "animals"){
dir = new File("animals/");
blah = ...;
blah2 = ...;
}
else if (typeIs == "sports"){
//same variables
}
//same thing for the other categories
假设上面的代码运行。
不,没有性能或内存差异。但就设计和惯用的scala代码而言,可变状态是糟糕的。最好使用第一个。