我正在做一个 scala 任务来完成这个:
observeCounter 函数有一个参数 f:一个接受(引用)Counter 实例但不返回任何内容的函数。 observeCounter 函数应该使用(引用)一个对象(属于扩展 Counter 的类)来调用 f。 扩展 Counter 的类必须跟踪调用递增/递减的总次数。 也就是说,如果增量方法在一个实例上被调用了 3 次,而减量方法在同一个实例上被调用了 2 次,那么它应该存储 5(除了现有字段 n 之外的其他地方)。 observeCounter 应该调用 f,然后返回 f 对实例调用增量/减量的总次数。
class myCounter extends Counter {
val total = 0
def increment () = {increment(); total = total + 1;}
def decrement () = {decrement(); total = total + 1;}
def get() : Int = total
}
def observeCounter (f : Counter => Unit) : Int = {
val o1 = new myCounter()
f(o1)
o1.get()
}
要求之一是使用 val 而不是 var。我不知道如何做到这一点。有什么建议吗?
最佳答案
我现在看到的最简单的方法是:
class myCounter extends Counter{
object counter{
var count = 0
}
val total = counter
def increment () = {super.increment(); total.count+=1}
def decrement () = {super.decrement(); total.count-=1;}
def get() : Int = total.count
}
关于Scala 使用 val 作为计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42497224/