Lesson contents

Scala — Organizing code across files

In Scala, a package gives names a namespace and an object provides a single helper instance. Import the object to call its method from another file.

A simple example

Import a function

  1. Start with −2
  2. Do this Import scala.math.abs
  3. Result 2
The imported name calls the absolute value function. Two units separate −2 from zero.
Lesson.scala
import scala.math.abs
object Lesson extends App {
    println(abs(-2))
}
Output
2
Advertisements

Share a function between source files

A package places BoxMath in a namespace and an object supplies one shared instance. The entry point imports the object and calls its method. These commands use the classic Scala 2.13 tools.

Room capacity: 8 seats. Already booked: 3 seats. Helper returns: 5 free seats.
Share a room-capacity calculation

A club ticket desk has eight seats and three bookings. Keep the calculation in a helper file so both the booking screen and the check-in screen can use it. With the same inputs, each reports five places left.

Run the example

Scala 2.13 with JDK 11 or later. Run these commands from the directory containing the example.

scalac Boxes.scala Lesson.scala
scala Lesson
Boxes.scala
package boxes

object BoxMath {
  def remaining(capacity: Int, used: Int): Int = capacity - used
}
Lesson.scala
import boxes.BoxMath

object Lesson {
  def main(args: Array[String]): Unit = println(BoxMath.remaining(8, 3))
}
Output
5

Create the files with the names shown and run the command from their common project folder. The entry point gives the helper a capacity of 8 and a used count of 3. The helper returns 5.

Try it yourself

Change the used count from 3 to 8 in the caller.

Check your answer

Running the same command prints 0. No change to the helper is needed.

Tour of Scala

Related tags

  • Scala
  • modules
  • source files
  • imports