“Static” field in Scala companion object

2019-03-02 08:30发布

Can I check the value of field in companion object without referring to class' actual object?

I'd like to store a static counter, increase it everytime new object of that class is created and be able to check it's value without using object itself, is this possible?

2条回答
孤傲高冷的网名
2楼-- · 2019-03-02 08:57

Is this what you want?

   object Foo {
        private var counter = 0
        private def increment = {
           counter += 1; 
           counter
        }
    }

    class Foo {
        val i = Foo.increment
        println(i)
    }
查看更多
何必那么认真
3楼-- · 2019-03-02 09:03
import java.util.concurrent.atomic.AtomicInteger
object Foo {
  val counter = new AtomicInteger(0)
}
class Foo {
  val i = Foo.counter.incrementAndGet()
  println(i)
}
查看更多
登录 后发表回答