title: How to implement a counter in functional programming way
body: <p>While trying to understand companion objects, I have written following code which counts the number of times a class was instantiated. I had to use a 'var' to keep the count. Is there a 'functional programming' way to achieve the same task i.e. use immutable variables.</p>
  
  <pre><code>class C {
    C.counter+=1
    def someCFunction = {println ("some C function. Counter is "+C.counter)}
  }
  
  object C{
    var counter:Int=0 //I do not want to use var
  }
  
  val c1 = new C
  c1.someCFunction
  
  val c2 = new C
  c2.someCFunction
  </code></pre>