Scala – Common code in package object

In the previous chapter, we have learnt about companion object in scala. Now, we will see what is a package object.

Main objective of a package is to keep files structured and easy to be maintained.What if , You want to make Scala functions, fields, and other code available at a package level, without requiring a class or object.

The solution is that put the code in package object so that code will be available to all classes within a package. Package objects were introduced in scala version 2.8.

By convention, put your code in a file named package.scala in the directory where you want to make your code available to other classes as well. Suppose, you want the code to be available to all classes inside main.com.testingpool package, then create a file named package.scala in the directory main/com/testingpool of your project.

Example:

// in file main/com/testingpool/Hollywood.scala

package main.com.testingpool

object Hollywood {

  val movie = "Titanic"
  val actor = "leonardo dicaprio"

}

// in file main/com/testingpool/Bollywood.scala

package main.com.testingpool

object Bollywood {
   val movie = "Dangal"
   val actor = "Amir Khan"

}

Create a package object in package.scala file at the same directory.

package main.com

package object movies {

  def printMovie(actor: String,movieName:String): Unit ={
    println("Actor "+ actor + " has worked in the movie "+movieName +".")
  }

}

Create main object where the program will start executing. You will see here, we have imported the package object by using a wildcard import on package main.com._. We have called its method named movies.

package main.com.testingpool

import main.com._

object AllMovies extends App{

  movies.printMovie(Hollywood.actor.toUpperCase,Hollywood.movie.toUpperCase)
  movies.printMovie(Bollywood.actor.toUpperCase,Bollywood.movie.toUpperCase)

}
Output - 
Actor LEONARDO DICAPRIO has worked in the movie TITANIC.
Actor AMIR KHAN has worked in the movie DANGAL.

Package objects are like other objects, which means you can use inheritance for building them. For example, one might inherit couple of traits:

package object movies extends movieWorld with movieUniverse{.....
}

Each package is allowed to have only one package object with the corresponding directory directory/package name.

+—main
 	+—com
		+—testingpool
			+—package.scala

+—main
 	+—com
		+—SecondPackage
			+—package.scala

Note that method overloading doesn’t work in package objects.

Avatar photo

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...