What does the Object clause define in Scala?

Asked

Viewed 34 times

0

Studying some projects, I found an intriguing code, where in addition to the clause class that defines an object, already known from Java, there is the clause object, unknown to me until then.

object Counter {
  val InitialValue = 10000000L; // (ten million)
  val CounterKey = "counter"
}

@Singleton
class Counter @Inject()(
  client: JedisClient) {

  def next: Long = {
    val current: Long = Option(client.get(CounterKey)) match {
      case Some(value) =>
        value.toLong
      case None =>
        InitialValue
    }
    val nextValue = current + 1
    client.set(CounterKey, nextValue.toString)
    nextValue
  }
}

What the object Counter defines in this case?

1 answer

1


The statement object introduces the object called Singleton, which is a class that will have only a single instance. The above statement builds both the class called Counter and its instance, also called Counter. This instance is created on demand at the time of its first use.

Example with method main:

object HelloWorld {
    def main(args: Array[String]) {
        println("Hello, world!")
    }
}

In this example it is possible to notice that the main method code is not declared as static here. This occurs because static members (methods or fields) do not exist in Scala. Instead of using static methods, the Scala programmer declares these members as Singleton objects.

What the Object Counter defines?

It defines two variables InitialValue and CounterKey that are static.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.