In Scala, packages act as containers for almost everything we can define inside a class.
Previous versions of Scala didn’t support such features with packages, but now we can include anything inside a package object.
Only one package object is allowed for each package. Any definitions stored in a package object will be recognized as members of the package.
Package objects in Scala support mixed inheritance, meaning a single object can extend more than one class or trait.
Package objects should be kept in a separate file (i.e., package.scala
) in the package that it communicates. Additionally, package objects enable variables, definitions, classes, or objects accessible to the entire package.
Let’s create a class Person,
which includes various attributes such as name,
age,
designation
, etc.
Suppose the name of the project is company,
so the package and package object for its class would be as follows:
package company.personcase class Person(name: String, age: Int, desig: String)object Male extends Person("Ahmad", 27, "Technical lead")object Female extends Person("Nida", 24, "Edpresso Intern")package companypackage object person {val employee = List(Male, Female)def showEmployee(person: Person): Unit = {println(s"${person.name}is ${person.age}years old and is a ${person.desig}")}}
In the code snippet above, the package object person
is named after the case class Person
. In addition, the package object includes a method definition showEmployee()
that prints the details mentioned in object Male
and object Female.
Free Resources