6.7. Putting Common Code in Package Objects

Problem

You want to make functions, fields, and other code available at a package level, without requiring a class or object.

Solution

Put the code you want to make available to all classes within a package in a package object.

By convention, put your code in a file named package.scala in the directory where you want your code to be available. For instance, if you want your code to be available to all classes in the com.alvinalexander.myapp.model package, create a file named package.scala in the com/alvinalexander/myapp/model directory of your project.

In the package.scala source code, remove the word model from the end of the package statement, and use that name to declare the name of the package object. Including a blank line, the first three lines of your file will look like this:

package com.alvinalexander.myapp

package object model {

Now write the rest of your code as you normally would. The following example shows how to create a field, method, enumeration, and type definition in your package object:

package com.alvinalexander.myapp

package object model {

  // field
  val MAGIC_NUM = 42

  // method
  def echo(a: Any) { println(a) }

  // enumeration
  object Margin extends Enumeration {
    type Margin = Value
    val TOP, BOTTOM, LEFT, RIGHT = Value
  }

  // type definition
  type MutableMap[K, V] = scala.collection.mutable.Map[K, V]
  val MutableMap = scala.collection.mutable.Map
}

You can now access this code directly from within other classes, traits, and objects ...

Get Scala Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.