Scala adopts the package concept that Java uses for namespaces, but Scala offers more flexibility. Filenames don’t have to match the type names and the package structure does not have to match the directory structure. So, you can define packages in files independent of their “physical” location.
1. Defines class in a package using the conventional Java syntax
// src/main/scala/progscala2/typelessdomore/package-example1.scala
package com.example.mypkg
class MyClass {
// ...
}
2. Defines classes in packages using block-structured syntax
// src/main/scala/progscala2/typelessdomore/package-example2.scala
package com {
package example {
package pkg1 {
class Class11 {
def m = "m11"
}
class Class12 {
def m = "m12"
}
}
package pkg2 {
class Class21 {
def m = "m21"
def makeClass11 = {
new pkg1.Class11
}
def makeClass12 = {
new pkg1.Class12
}
}
}
package pkg3.pkg31.pkg311 {
class Class311 {
def m = "m21"
}
}
The package pkg3.pkg31.pkg311
shows that you can “chain” several packages together in one statement. It is not necessary to use a separate package statement for each package.
3. Using separate package name
However, there is one situation where you might use separate statements.
// src/main/scala/progscala2/typelessdomore/package-example3.scala
// Bring into scope all package level declarations in "example".
package com.example
// Bring into scope all package level declarations in "mypkg".
package mypkg
class MyPkgClass {
// ...
}
If you have package-level declarations, like types, in each of several parent packages that you want to bring into scope, use separate package statements as shown for each level of the package hierarchy with these declarations. Each subsequent package statement is interpreted as a subpackage of the previously specified package, as if we used the block-structure syntax shown previously.
4. Note
Packages can not be defined within classes and objects, which wouldn’t make much sense anyway.
Ref