Desktop version

Home arrow Computer Science arrow Building Applications with Scala


Package objects

Scala has packages like Java. However, Scala packages are also objects, and you can have code inside a package. Java does not have the same power as Scala in terms of packages. If you add code to a package, it will be available to all classes and functions within that package.


Your package.scala file should contain the following code


package object commons { val PI = 3.1415926 object constraintsHolder { val ODD = "Odd" val EVEN = "Even"


def isOdd(n:Int):String = if (n%2==0) constraintsHolder.ODD else


def isEven(n:Int):String = if (n%2!=0) constraintsHolder.EVEN else null

def show(s:String) = println(s)


This is the Scala package object. There is this special token called package object which you use to define common code to all classes, objects, and functions that are defined inside this package or sub-package. For this case, we define a value of PI as a constant and also one object holder containing the String values for Odd and Even. There are also three helper functions, which can and will be used by the classes inside this package.

Found a mistake? Please highlight the word and press Shift + Enter  
< Prev   CONTENTS   Next >

Related topics