Scala 中的全局变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19241006/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Global Variables in Scala
提问by Learner
I'm new to Scala and functional programming for that matter. I'm trying to use the functionality of global variables inside my main() functions like this,
我是 Scala 和函数式编程的新手。我正在尝试在我的 main() 函数中使用全局变量的功能,如下所示,
object Scala_Object {
var myDict = scala.collection.mutable.Map[String,String]()
def str_rev(s : String) : String = {
myDict.put(s,s.reverse)
return (s.reverse)
}
def main (args: Array[String]){
..
..
val result = parsedArray.map(line => line.map { word =>
if( word == "") word
else if(word == line(2) || word == line(3)) str_rev(word)
else if ( word == line(1) || word == line(26)) str_rev(word)
else word})
}
At the end of my program only elements from my first line from parsedArray( which is an Array[Array[String]]) is added to the dict - myDict. Is there anything that I'm missing ? I noticed that there isn't doc/tutorial on Global variables, so I presume there is fundamentally No concept called Global variables in SCALA. Then, how is the concept of global variables handled in Scala ?
在我的程序结束时,只有来自 parsedArray(这是一个Array[Array[String]])的第一行的元素被添加到 dict - myDict。有什么我想念的吗?我注意到没有关于全局变量的文档/教程,所以我认为 SCALA 中根本没有称为全局变量的概念。那么,Scala 中如何处理全局变量的概念呢?
回答by fresskoma
Your example should work fine. If there's a problem, it doesn't seem to be in the code you've posted. As a side note, your myDictdoes not need to be a varsince you don't want to re-assign it. The varand valkeywords in Scala refer not to the referenced object or class instance, but to the reference, for example:
您的示例应该可以正常工作。如果有问题,它似乎不在您发布的代码中。作为旁注,您myDict不需要是 avar因为您不想重新分配它。Scala 中的varandval关键字不是指被引用的对象或类实例,而是指引用,例如:
val x = 5
x = 6 // This will fail, reassignment to val
var y = 3
y = 5 // This works
val z = mutable.Map[String,String]()
z.put("foo", "bar") // This works because the reference is not modified
z = mutable.Map[String,String]() // This fails
Here's how you test your Scala_Objecton the Scala console:
以下是Scala_Object在 Scala 控制台上测试您的方法:
scala> :paste
// Paste the code of your Scala_Object here
// And press Ctrl-D
defined module Scala_Object
scala> Scala_Object.myDict
res1: scala.collection.mutable.Map[String,String] = Map()
scala> ScalaObject.str_rev("foo")
res4: String = oof
scala> ScalaObject.myDict
res5: scala.collection.mutable.Map[String,String] = Map(foo -> oof)
scala> ScalaObject.str_rev("lol")
res6: String = lol
scala> ScalaObject.myDict
res7: scala.collection.mutable.Map[String,String] = Map(lol -> lol, foo -> oof)

