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

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

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

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 objects are like other objects, which means you can use inheritance for building them. For example, one might inherit couple of traits:

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

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

Scala - Companion Object
Scala - Primary Constructor
Shekhar Sharma

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. He is an automation engineer having more than 8 years of experience who loves troubleshooting in automation and finding innovative ways to solve the problems. His other leisurely activities includes playing harmonica, paintings, sketching portrait, watching movies and travelling etc.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *