在 Scala 中声明一个全局变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31355258/
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
Declare a global variable in scala
提问by user582040
Is it possible to declare a global variable in this way?
是否可以以这种方式声明全局变量?
if i run this snippet, i will encounter an error
如果我运行这个片段,我会遇到一个错误
object Test {
val value -> error on this line for declaration issue
def run() {
value = ...
}
def main(args: Array[String]) {
run()
}
thanks in advance.
提前致谢。
回答by mfirry
You could in theory do it using a Trait. I'm not sure this is what you need though.
理论上你可以使用Trait 来做到这一点。我不确定这是你需要的。
It would look like this:
它看起来像这样:
trait MyTestTrait {
val value: String
}
object MyTest extends MyTestTrait {
val value = "yo!"
def run = println(value)
}
回答by Madoc
No, that's not possible. You should do this:
不,那不可能。你应该做这个:
object Test {
val value = ...
}
Since your run()function does not take parameters, the contents of valuecan also be computed without it.
由于您的run()函数不接受参数,value因此也可以在没有参数的情况下计算的内容。

