Chapter 9. Packaging and Imports
Packages are used to build related modules of code, and to help prevent namespace collisions. In their most common form, you create Scala packages using the same syntax as Java, so most Scala source code files begin with a package declaration, like this:
packagecom.alvinalexander.myapp.modelclassPerson...
However, Scala is also more flexible. In addition to that approach you can use a curly brace packaging style, similar to C++ and C# namespaces. That syntax is shown in Recipe 9.1.
The Scala approach to importing members is similar to Java, and more flexible. With Scala you can:
-
Place import statements anywhere
-
Import packages, classes, objects, and methods
-
Hide and rename members when you import them
All of these approaches are demonstrated in this chapter.
Before jumping into those recipes, it helps to know that two packages are implicitly imported into the scope of all of your source code files:
-
java.lang.* -
scala.*
In Scala 3 the * character in import statements is similar to the * character in Java, so these statements mean “import every member” in those packages.
The Predef object
In addition to those two packages, all members from the scala.Predef object are also implicitly imported into your source code files.
If you want to understand how Scala works, I highly recommend taking a little time to dig into the Predef object source code. The code isn’t too long, and it demonstrates many of the features of the Scala language. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access