scala> object Test
defined module Test
Why is the defined object Test
called 'module', not companion object, by the scala interpreter ?
Is there a difference between module and companion object or is it just the same with two different names ?
A "module" is a pluggable piece of software, also called a "package" sometimes. It provides a functionality through a well-defined set of interfaces, which declare what it provides and what it requires. Finally, it is interchangeable.
In Scala, an object of a class is created using the new keyword. The syntax of creating object in Scala is: Syntax: var obj = new Dog();
A companion object is an object that's declared in the same file as a class , and has the same name as the class. A companion object and its class can access each other's private members. A companion object's apply method lets you create new instances of a class without using the new keyword.
Instead of static keyword Scala has singleton object. A Singleton object is an object which defines a single object of a class. A singleton object provides an entry point to your program execution. If you do not create a singleton object in your program, then your code compile successfully but does not give output.
Technically, there is only one such thing, in the language specification it is mostly called 'module', but you also find this statement: "The object definition defines a single object (or: module) ..." (Scala Language Specification)
Furthermore, you can only speak of a companion object, when it actually accompanies something:
"Generally, a companion module of a class is an object which has the same name as the class and is defined in the same scope and compilation unit. Conversely, the class is called the companion class of the module." (again think: companion object = companion module)
Being in companion state adds features to the companion class, namely visibility (e.g., the class can see the private fields of the companion module). Same scope and compilation unit means, they need to be defined in the same source file and same package.
There is an interesting thread on LtU where Scala's object versus module terminology is discussed. It contains also a link to a paper by Odersky and Zenger if you are intrigued; showing how they particularly looked at the ML language's module system (OCaml being a major influence on Scala), and how they frame it as various approaches of modular composition (suggesting that module is a more generic concept; traits as mixin modules, ...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With