What does the object clause define in Scala?

0

By studying some projects, I found an intriguing code, where in addition to the class clause that defines an object, already known in Java, there is the object clause, 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 does object Counter define in this case?

    
asked by anonymous 31.03.2017 / 00:15

1 answer

0

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 you can see that the main method code is not declared as static here. This is because static members (methods or fields) they do not exist in Scala. Instead of using static methods, the Scala programmer declares these members as singleton objects.

What does the object Counter define?

It defines two variables InitialValue and CounterKey that are static.

    
10.04.2017 / 14:22