tom*_*myk 6 c++ scala static-variables
我对Scala很新,偶然发现以下问题:
什么是Scala相当于函数的静态变量?
void foo()
{
static int x = 5;
x++;
printf("%d", x);
}
Run Code Online (Sandbox Code Playgroud)
编辑:
我想要实现的是一种函数调用计数器 - 我想检查我的函数执行了多少次,同时限制了这个计数器的可见性,以便它不能从外部修改.
ped*_*rla 18
这是一段具有类似效果的代码:
scala> object f extends Function0[Unit] {
| var x = 0;
| def apply = {
| x = x + 1;
| println(x);
| }
| }
defined module f
scala> f()
1
scala> f()
2
Run Code Online (Sandbox Code Playgroud)
虽然我必须强调这是一种非常糟糕的做法,因为它会杀死参考透明度.
如果你真的需要这种行为,请考虑这个:
type State = Int
def f(state: State) = {
val newState = state + 1
println(state);
newState;
}
Run Code Online (Sandbox Code Playgroud)