mocode9
mocode9

Reputation: 239

Scala using val as a counter

I'm working on a scala task to accomplish this:

The observeCounter function has one parameter f: a function that accepts (a reference to) a Counter instance but returns nothing. The observeCounter function should call f with (a reference to) an object (of a class extending Counter). Your class that extends Counter must keep track of the total number of times that increment/decrement have been called. I.e., if the increment method is called 3 times on an instance, and the decrement method is called 2 times on the same instance, then it should store 5 (somewhere other than the existing field n). observeCounter should call f, and then return the total number of times that increment/decrement were called on the instance by 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()
}

One of the requirements is to use val and not var. I have no clue how to accomplish that. Any suggestions?

Upvotes: 3

Views: 8246

Answers (2)

Kamil Banaszczyk
Kamil Banaszczyk

Reputation: 1153

The easiest way which i see right now to achieve this is:

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
}

Upvotes: 1

clay
clay

Reputation: 20410

You have two options. Either you use a persistent immutable, where f() returns an updated copy of the Counter, or you use a mutable data structure, where you use var, or use a workaround where you use val to wrap a var with a single element array or an AtomicInteger or something similar.

Upvotes: 0

Related Questions