O'Reilly logo

Building Applications with Scala by Diego Pacheco

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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.

package.scala

Your package.scala file should contain the following code

    package com.packait.scala.book 
 
    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 
      null   
 
      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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required