11 Singleton Objects
After reading this lesson, you will be able to:
- Implement a singleton object
- Use objects as executable programs
- Define static functions in a companion object
- Create factory methods using the apply function
The essence of Object-Oriented Programming is representing elements of the real world using classes that describe their behavior through methods. In specific scenarios, such as configurations and main entry points, you need to instantiate a coding element at most once: you usually call it “singleton”. In Scala, you can create singletons using objects elegantly and concisely. You are also encouraged to make a clear separation between static and non-static methods: the non-static ones act on a specific instance of a class, while the static ones belong to its general definition. In Scala, you implement non-static methods in a class and static methods in an object. In the capstone, you’ll use an object to define the main entry point of your application.
11.1 Object
Consider the following class to represent a robot:
abstract class Robot(name: String) { def welcome: String }