An object in Scala has a slightly different meaning than the traditional OOP one, and this difference should be explained. In particular, in OOP, an object is an instance of a class, while in Scala, anything that is declared as an object cannot be instantiated! The object is a keyword in Scala. The basic syntax for declaring an object in Scala is as follows:
object <identifier> [extends <identifier>] [{ fields, methods, and classes }]
To understand the preceding syntax, let's revisit the hello world program:
object HelloWorld {
def main(args : Array[String]){
println("Hello world!")
}
}
This hello world example is pretty similar to the Java ones. The only big difference is that the main method is not inside a class, but instead it's inside an object. In Scala, the keyword object can mean two different things:
- As in OOP, an object can represent an instance of a class
- A keyword for depicting a very different type of instance object called Singleton