Scala – Packages

  • date 24th April, 2021 |
  • by Prwatech |
  • 0 Comments

Packages and Imports Tour of Scala

 

In Scala , packages are used to build namespaces which permits you to modularize programs.

Scala Packages are created by creating one or more package at the top of a Scala file.

use case 1:

Create package prwa and then class faculty

package prwa

class faculty {

  def faculymethod(){}

}

Now create class student under same package prwa

package prwa

// using the prwa package name again

class student {

  def studentmethod(){}

}

object Main

{

    // Main method

    def main(args: Array[String])

    {

        val stu= new student()

        val fac= new faculty()

        // faculty class can be accessed while

        // in different file but in same package.

        println("welcome to prwatech")

    }

}

The directory structure looks like as below

prwa

       +faculty.scala

       +student.scala

output

The value of z after casting into Int is 0

use case 2:

package eduprwa

class Fruit {

  def Fruitmethod(){}

}

Create another class under same package

package eduprwa

class FruitName {

  def FruitNamemethod(){}

}

object Main

{

 def main(args: Array[String])

 {

   val Fruit= new Fruit()

   val FruiName= new FruitName()

   // FruitName class can be accessed while

   // in different file but in same package.

   println("Mango is a Fruit")

 }

}

output

Mango is a fruit

use case 3:

package prwatech

class Institute {

  private var id=2

    def method()

  {

    {

        println("welcome to Data Science Training")

        println("id="+id)

 

//

package tech

object Main {

  def main(args: Array[String])

  {

        // importing in main method

        import prwatech.Institute

        // using the member injected using import statement

        val obj = new Institute()

        obj.method();

 

output

welcome to Data Science Training
id=2

Packages and Imports Tour of Scala

Quick Support

image image