alain
1
I tried the following code to count the number of class instances. But it returns 1 instead of the correct value 3.
package com.alain
class MyClass(var x:Int) {
}
object MyClass {
var counter : Int = 0
counter = counter +1
}
object Main {
def main(args: Array[String]): Unit =
println("Start")
var c:MyClass = MyClass(1)
var d:MyClass = MyClass(2)
var e:MyClass = MyClass(3)
println(MyClass.counter)
println("Stop")
}
alain
2
I found the solution :
package com.alain
object MyClass {
var counter: Int = 0
}
class MyClass(var x: Int) {
MyClass.counter = MyClass.counter + 1
}
object Main {
var c: MyClass = MyClass(1)
var d: MyClass = MyClass(2)
var e: MyClass = MyClass(3)
def main(args: Array[String]): Unit = println("Start")
println(MyClass.counter)
println("Stop")
}
3 Likes
xolve
3
Also make counter
’s type to be AtomicInteger
to prevent race conditions in case object creations are across threads.
1 Like