Open In App

Scala | Package Objects

Main objective of a package is to keep files modularized and easy to be maintained. So we keep project files in several different folder or directories according to the namespace created, but sometimes we want to some variable, definitions, classes or objects to be accessible to entire package. But its not possible to keep definitions, data variables and type aliases directly in a package. To do so we have package object, so that the common data can be at the top level of the package. Package objects were introduced in scala version 2.8. Syntax:

package projectx
package src
package main
object `package`
{
  // using backticks
  val x
  // members
}

or standard way to do it is.



package src
package object main
{
  val x
  // members
}

In the above Syntax all the member of the package object are available to all the class in projectx.src.main package and this file would be saved as package.scala in the directory/package “main” which corresponding to the package name as well. Example: Lets have a package object GFG with path as follows:-

File Path: ../src/language/GFG/package.scala
package language
package object GFG 
{
  val fees = "fees"
  val tax = "tax"
}

Another file GFG.scala with the main method in it.



File Path: ../src/language/GFG/GFG.scala




package language.GFG
 
object GFG
{
  val scala = "scala"
  val java = "java"
  val csharp = "csharp"
}
 
object demo
{
  def main( args : Array[String])
  {
    println(GFG.scala)
    println(GFG.csharp)
    var totalfees= tax + fees
    println(totalfees)
  }
}

Explanation: As we can see that we have tax and fees directly available to use because GFG.scala and package.scala are at the same level.

+src
   +language
        +GFG.scala
        +package.scala




// Scala program of package object
 
// package eatables.food
 
// Object created
object GFG
{
    val scala = "scala"
    val java = "java"
    val csharp = "csharp"
}
 
// Object created
object demo
{
    // Driver code
    def main( args : Array[String])
    {
        println(GFG.scala)
        println(GFG.csharp)
        var totalfees = tax + fees
        println(totalfees)
    }
}
 
// package object created
object `package`
{
    val fees= "fees"
    val tax= "tax"
}

Output:

scala
csharp
taxfees
Package objects Important points
package object main extends demovars
{
  val x = a // from demovars
  val y = b // from demovars
  // members
}
package object main
{
  val x = demovars.a // from demovars
  val y = demovars.b // from demovars
  // members
}
+src
   +eatables
        +food.scala
        +package.scala // package object for eatables folder
  +drinkables
        +drinks.scala
        +package.scala // package object for drinkable folder

Article Tags :