August 2018
Intermediate to advanced
380 pages
10h 2m
English
In Scala, it is impossible to make a class have static members. However, the concept of a static member is present in Java. Since Scala compiles to JVM, it needs a way to model this concept from Java. In Scala, a concept of a singleton object is used to model static members:
scala> :paste// Entering paste mode (ctrl-D to finish)object Foo { def say = println("I am Foo")}// Exiting paste mode, now interpreting.defined object Fooscala> Foo.sayI am Foo
In the preceding code, we can call the members of the singleton object without instantiating it or doing anything else with it, directly by its name. This is because it is a standalone fully fledged object that is constructed by our object statement. It exists in a single instance ...