Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

scala

What are package objects in Scala?

Dian Us Suqlain

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.

Code

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

case 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 company 
package 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}")
  }
}
Package object in Scala

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.

Package Object in Scala

RELATED TAGS

scala

CONTRIBUTOR

Dian Us Suqlain
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring