O'Reilly logo

Pragmatic Scala by Venkat Subramaniam

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Using Singletons and Companion Objects from Java

Scala compiles singleton and companion objects into a “singleton class” with a special $ symbol at the end of its name. Scala, however, treats a singleton and a companion object differently, as you’ll soon see.

When compiled, a Scala singleton turns into a Java class with static methods at the bytecode level. In addition, another regular class with methods that forward calls to the singleton class is created. So, for example, this code defines a singleton object Single, and Scala creates two classes, Single$ and the forward class Single:

Intermixing/Single.scala
 
object​ Single {
 
def​ greet() { println(​"Hello from Single"​) }
 
}

We can use the singleton object from Java as we’d use any Java ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required