Package Objects in Scala was introduced as part of Scala 2.8. With this feature a package in scala can contain field declarations, methods along with the classes, objects and traits. The methods and variable declarations are put into the package object and are accessible in the package for which the package object was declared.
also read:
Let’s take a look at very simple example.
//File: TestClass.scala package net{ package javabeat{ class TestClass{ def instanceMethod():String = { println("From TestClass: "+packageMethod1) "Invoked instance method" } } object TestClass extends App{ val testObj = new TestClass println(testObj.instanceMethod) println(packageMethod1) println(packageField1) } } } package net{ package object javabeat{ def packageMethod1():String = { "Invoked Package Method1" } val packageField1 = "Package Field1" } }
Unlike Java, in Scala the packages can be nested, something like show in the above example. The package declaration in the above example can also be written as net.javabeat. And Scala doesn’t enforce the classes declared in a package should be placed in the same directory structure. One could have all the classes in the same folder but when you compile the source, it creates the class files in the directory structure as per the package name.
In the above example we declared a package object using the syntax package object. We declared a method packageMethod1 and a field packageField1 in the package object javabeat. In the class TestClass defined in the package net.javabeat we try to access the method defined in the package object.
Someone very new to Scala would wonder about the following code:
object TestClass extends App{ val testObj = new TestClass println(testObj.instanceMethod) println(packageMethod1) println(packageField1) }
The above code creates a companion object for the class TestClass. The companion object is nothing but a singleton instance for the class for which it is a companion object. And the companion object can extend other classes, and also mixin traits. We extended the App object which wraps the code within the object declaration into a main method.
In short the methods, fields declared in the package object are accessible throughout the package.
Lets compile and run the above code:
$ scalac TestClass.scala $ scala net.javabeat.TestClass From TestClass: Invoked Package Method1 Invoked instance method Invoked Package Method1 Package Field1
If you get the following error:
TestClass.scala:15: error: not found: type App object TestClass extends App{ ^ one error found
Then you need to use the latest Scala version or you can replace extends App with extends Application.