As is described, better to provide a concrete example that package object can do but object can not.
A package object lets you put vals and defs in the same namespace as top-level things that are subject to separate compilation
I have create an object just like the package object imported in every scala file as below.
object scalaLike {
type Seq[+A] = scala.collection.Seq[A]
val Seq = scala.collection.Seq
type List[+A] = scala.collection.immutable.List[A]
val List = scala.collection.immutable.List
//............blablabla...
}
And I use it in my own code just like scala package object.
package recruit.scalar.com.elevenbee.Exercise.Chapter19.queue
import recruit.scalar.com.elevenbee.Exercise.Chapter19.scalaLike._
trait Queue[+T] {
def head:T
def tail:Queue[T]
def appendU>:T:Queue[U]
}
object Queue{
def apply[T](xs: T*): Queue[T] = new QueueImplT()
private class QueueImpl[T](private val leading:List[T],private val trailing:List[T]) extends Queue[T]{
def mirror=
if (leading.isEmpty)
new QueueImpl(trailing.reverse,Nil)
else
this
override def head: T = mirror.leading.head
override def tail: Queue[T] = {
val q=mirror
new QueueImpl(q.leading.tail,q.trailing)
}
override def append[U >: T](x: U): Queue[U] = new QueueImpl[U](leading,x::trailing)
}
}
I didn’t see any difference between object and package object in this example.
A package is open, while an object is closed. Meaning that you can add classes to a package in different files. The entire contents of an object have to be defined in the same file.
A package object is a way to add top level val
, def
, var
or type
members to a package.