What is the difference between package and object?
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).
To add a bit to Daniel's answer:
From the Scala specifications:
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.
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:
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