Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use package and when object in Scala?

What is the difference between package and object?

like image 875
Łukasz Lew Avatar asked May 09 '10 00:05

Łukasz Lew


2 Answers

Packages are not run-time entities, objects are. You should use packages to organize the hierarchy of your code, and objects whenever you need something to store code or data (assuming plain classes and instances are not better, of course).

like image 96
Daniel C. Sobral Avatar answered Sep 22 '22 03:09

Daniel C. Sobral


To add a bit to Daniel's answer:

From the Scala specifications:

Objects

Classes (§5.3) and objects (§5.4) are both defined in terms of templates.
A template defines the type signature, behavior and initial state of a trait or class of objects or of a single object.

It can have:

  • local modifiers (‘abstract’, ‘final’, ‘sealed’, ‘implicit’, ‘lazy’)
  • access modified (‘private’ | ‘protected’),
  • access qualifier (‘this’)

An object definition defines a single object of a new class (or: module) conforming to the template t.
It is roughly equivalent to the following three definitions, which together define a class and create a single object of that class on demand:

final class m$cls extends t
private var m$instance = null
final def m = {
  if (m$instance == null) m$instance = new m$cls
  m$instance
}

An object can isolate a code common for other Class instances.. A specific usage:

Classes in Scala do not have static members; however, an equivalent effect can be achieved by an accompanying object definition.
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.


Packages

a package is part of compilation unit.

A compilation unit consists of a sequence of packagings, import clauses, and class and object definitions, which may be preceded by a package clause.

A package is a special object which defines a set of member classes, objects and packages.

Unlike other objects, packages may not be used as values. It is illegal to have a package with the same fully qualified name as a module or a class.
Top-level definitions outside a packaging are assumed to be injected into a special empty package. That package cannot be named and therefore cannot be imported.

The special predefined name _root_ refers to the outermost root package which contains all top-level packages.


So:

  • object organize code to be executed from a unique runtime instance.
  • package declare code namespace for the compilation step.
like image 39
VonC Avatar answered Sep 22 '22 03:09

VonC