Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a defined object called 'module' by the Scala interpreter?

Tags:

module

scala

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 ?

like image 289
John Threepwood Avatar asked Jun 29 '12 17:06

John Threepwood


People also ask

What is a module in Scala?

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.

How do you define an object in Scala?

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();

What is the use of companion object in Scala?

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.

What is the use of singleton object in Scala?

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.


1 Answers

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, ...)

like image 73
0__ Avatar answered May 26 '23 18:05

0__