Home » Scala language

Packages in Scala

Packages are ways to encapsulate classes, traits and package objects. In this tutorial, we will learn about packages in Scala and their usage.
Submitted by Shivang Yadav, on December 24, 2019

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 a Package in Scala

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 in Scala

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

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
    }

Example:

// package bike has other classes like harley, etc. 
package bike
class BMW {
    val bike_name;
    def display_name(){}
}
object MyClass {
    def main(args: Array[String]) {
        val gs310r = new BMW();
    }
}

Using packages in Scala

Packages are used to import members in Scala programming. The import keyword is used to add members in Scala.

Example:

// package bike has other classes like harley, etc. 
import bike
object MyClass {
    def main(args: Array[String]) {
        val gs310r = new BMW();
        val street750 = new harley(); 
    }
}






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.