Home »
Scala
Packages in Scala
By IncludeHelp Last updated : October 26, 2024
Scala Packages
In Scala, Packages are used to put classes, sub-packages, traits and other packages together. It is the namespace of code in files and directories in the Scala programming language. It is used to maintain code into folders isolating them from other members. Also, managing their access of members using access specifiers like public (when nothing is specified), package specific, protected, private.
Declaring Package
The first statement of a Scala programming is package declaration in Scala.
Syntax
package package_name
You can also define packages in some different ways in Scala,
package x.y.z
// or
package x
package y
package z
Working of Packages
Packages are files that are used to encapsulate data and storing data into files. Packages are similar to the directory structure. It will locate classes that are directories in easy-access locations.
The naming convention is reverse order for packages i.e. com.includehelp.scala.
Adding Members to a Package
In Scala, new members can be added to a package. Members like classes, subclasses, traits, objects, sub-packages. In Scala, you can add different files in the same package.
Syntax
package bike
class BMW {
val GS 310r
}
Using packages in Scala
Packages are used to import members in Scala programming. The import keyword is used to add members in Scala.
Syntax
import bike
Example of Scala Package
This example demonstrates the creation of a BMW
class within a bike
package and a MyClass
object that initializes instances of both BMW
and Harley
, showcasing how to organize classes in packages in Scala:
1. BMW.scala
package bike
class BMW(val bikeName: String) {
def displayName(): Unit = {
println(s"Bike Name: $bikeName")
}
}
2. Harley.scala
package bike
// Define a simple Harley class with a name
class Harley(val bikeName: String) {
def displayName(): Unit = {
println(s"Bike Name: $bikeName")
}
}
3. MyClass.scala
package bike // This line should match the package for consistency
object MyClass {
def main(args: Array[String]): Unit = {
// Pass a bike name to the constructor
val gs310r = new BMW("GS 310 R")
// Call the display method
gs310r.displayName()
// Create an instance of Harley
val street750 = new Harley("Street 750")
// Call the display method
street750.displayName()
}
}
Output
Bike Name: GS 310 R
Bike Name: Street 750
Code Explanation
- BMW.scala: We defined the
BMW
class with a constructor to initialize the bike's name and a method to display it.
- Harley.scala: We defined the
Harley
class with a constructor to initialize the bike's name and a method to display it.
- MyClass.scala: The main class file that contains the
main
method to create instances of BMW
and Harley
and displaying their names.