Desktop version

Home arrow Computer Science arrow Building Applications with Scala

Source

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 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.

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

Related topics