fanhk
fanhk

Reputation: 795

How to implement a class with a static self-increase member in Scala?

I want to implement a class using Scala like this:

class Ref(name: String, size: Int)

if I want to add a static member in this class I need add a componion object:

object Ref {
  private var id: Int = 0
}

Then, when I create an object such as val ref = new Ref("something", 20), How should I do to let the member "id" could self-increase (like id = id + 1)?

Upvotes: 1

Views: 132

Answers (2)

Sergii Lagutin
Sergii Lagutin

Reputation: 10671

Use AtomicInteger to avoid concurrent bug with incrementing id value.

object Ref {
  private val id = new AtomicInteger()

  def next = id.incrementAndGet()
}

class Ref(name: String, size: Int) {
  val id = Ref.next
}

Upvotes: 4

idursun
idursun

Reputation: 6335

You can increase the counter inside the primary constructor

object Ref {
  var id: Int = 0
}

class Ref {
   Ref.id = Ref.id + 1 
}

Upvotes: 0

Related Questions