Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 37 ยท Classes, Traits and Objects

Packages, Imports and Access Control

Learn Scala packages and imports (wildcards, renaming, selectors), package objects and top-level definitions, access modifiers private and protected, and qualified private[scope].

As programs grow you need to split them into files and keep names from colliding. Scala uses packages to organize code, imports to bring names into scope and access modifiers to hide details. The ideas resemble Java's, with a few improvements: imports can appear anywhere, names can be renamed on import, and access can be limited to a specific enclosing package or class. This lesson covers all of it. The Scala is read-only; runnable Java and Kotlin examples show the shared concepts.

Packages

Every file can start with a package clause. The package decides the full name of what you define:

SCALA
package shop.billing

class Invoice(val total: Double)

object Tax:
  def vat(amount: Double): Double = amount * 0.2

The full name of Invoice is shop.billing.Invoice. By convention the package name matches the directory (shop/billing/Invoice.scala), but Scala does not force this as Java does. You can also nest packages, or put several in one file:

SCALA
package shop:
  package billing:
    class Invoice
  package inventory:
    class Item

Because the compiler treats packages as namespaces, members of the same package see each other without imports. A package clause also makes the parent packages' members visible when you use the chained form package shop followed by package billing.

Importing

SCALA
import scala.collection.mutable.ArrayBuffer      // one name
import scala.collection.mutable.{ArrayBuffer, ListBuffer}   // several
import scala.collection.mutable.*                // everything (Scala 3 wildcard)
import scala.collection.mutable._                // same, Scala 2 spelling still accepted

Scala 3 uses * as the wildcard. Imports can be anywhere, not just at the top, which keeps the scope small:

SCALA
def parse(text: String): Int =
  import scala.util.Try
  Try(text.toInt).getOrElse(0)

Renaming and hiding

SCALA
import java.util.{List as JList, Map as JMap}   // rename on import
import java.util.*                              // all of java.util ...
import scala.collection.mutable.{Set as _, *}   // ... everything except mutable.Set

X as Y was X => Y in Scala 2. Renaming avoids clashes like java.util.List versus scala.List. The form Set as _ hides a name.

Automatic imports

These are always available without writing them:

  • everything in java.lang (String, Math, System),
  • everything in scala (List, Option, Int...),
  • everything in scala.Predef (println, Map, Set, require).

Java's import rules are close, and this runnable Java program shows renaming is not available there, which forces fully qualified names:

Java Name clash in Java (no import renaming)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

In Scala you would write import java.awt.{List as AwtList} once, then use AwtList freely.

Importing members of objects and givens

You can import members of an object, which is how you get the helpers without a prefix:

SCALA
import scala.math.{max, min, sqrt, Pi}
sqrt(16.0)      // 4.0
max(3, 9)       // 9

object Colors:
  val Red = "#f00"
  val Blue = "#00f"

import Colors.*
println(Red)     // #f00

In Scala 3, import X.* does not import given instances. You import them explicitly with import X.given. This avoids accidental implicit behaviour and is covered in the language's contextual abstractions.

Top-level definitions and package objects

In Scala 3 you can place values, methods and type aliases at the top of a file in a package, with no wrapper:

SCALA
package shop

val DefaultCurrency = "EUR"

def formatMoney(amount: Double): String = f"$amount%.2f $DefaultCurrency"

Anywhere in package shop you call formatMoney(3.5), and elsewhere you import shop.formatMoney. In Scala 2 you needed a package object for this (package object shop { ... }); it still works.

Access modifiers

By default, members are public: visible to everyone. There is no public keyword.

SCALA
class Wallet(private var cents: Int):
  def add(more: Int): Unit = cents += more
  def euros: Double = cents / 100.0
  private def audit(): Unit = println("audit")

val w = Wallet(500)
w.add(250)
w.euros      // 7.5
// w.cents   // error: cents is private
Modifier Visible to
(none) everyone
private the class (and its companion)
protected the class and its subclasses
private[this] (object-private) only the same instance; in Scala 3 largely replaced by plain private

Two Scala differences from Java:

  • protected members are not visible to the other classes in the same package. Only subclasses can use them.
  • A class and its companion object can read each other's private members, so factories can use private constructors.

Qualified access

You can name the scope that gets access, which is more precise than Java's package-private:

SCALA
package shop

class Order:
  private[shop] def internalId: Int = 7     // visible inside package shop
  protected[shop] def hook(): Unit = ()     // subclasses and package shop
  private[Order] def secret: Int = 1        // same as plain private

private[shop] is the closest relative of Java's default (package-private) access, but it can also name an outer package such as private[billing], so you choose how wide "internal" is. This is great for libraries: public API at the top, implementation details limited to the package.

Encapsulation example

A class that hides its mutable state and exposes safe behaviour:

SCALA
class Counter:
  private var value = 0
  def increment(): Unit = value += 1
  def current: Int = value

Outside code can read current and call increment(), but can never set the counter to an arbitrary number.

Kotlin's private and internal do the same job, runnable:

Kotlin Private state with a public API (Kotlin comparison)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Organizing a project

  • One main public type per file, named after the file (a convention, not a rule).
  • Group related files into packages, such as model, service, util.
  • Keep the public API small: mark everything else private or private[pkg].
  • Put imports in the smallest scope that works; avoid wildcard imports of big packages if names may clash.
  • Avoid cyclic dependencies between packages.

Common mistakes

  • Expecting protected to give package access as in Java.
  • Importing with _ in Scala 3 and getting a deprecation warning later; use *.
  • Creating deep package nests for tiny projects.
  • Making a field public (var) and then wanting to add validation. Start with private and a method.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the default access level of a member in Scala?

    Members are public unless you add a modifier; Scala has no public keyword.
  2. 2. How do you rename a class on import in Scala 3?

    Scala 3 uses import a.{B as C}; the old => form is Scala 2.
  3. 3. What does private[shop] mean?

    A qualifier names the enclosing scope that may access the member, here the shop package.
  4. 4. Which is true about protected in Scala?

    Scala's protected is limited to subclasses, unlike Java where it also includes the package.

Summary

  • Packages organize code into namespaces; the package clause need not match the folder, but it should by convention.
  • import a.*, import a.{B, C as D} and local imports control which names are in scope; java.lang, scala and Predef are imported automatically.
  • Scala 3 allows top-level val and def in a file; Scala 2 needed package objects.
  • Members are public by default; use private, protected and qualified forms like private[shop].
  • Companions can see each other's private members; keep state private and expose behaviour.

Next: Scala Case Classes