What are packages and imports in Scala?

Packages in Scala

Packages in any language, including Scala, are grouped under the same name. We use packages to increase the modularity of code.

package animals

Scala packages allow you to encapsulate classes, objects, traits, and methods inside a package name.

Note: The package name is always mentioned at the top of the program in lower case letters.

Example - Packages in Scala

Suppose we have a class named Animals. Its package name would be:

package animals

class Animals

Users can include multiple packages in a program as well.

package animals {

  package carnivorous {
    // class, methods or traits
  }
  package omnivorous {
    // class, methods or traits
  }
}
Packages and Import in Scala

Import in Scala

To include something in the code that is available in another class, we can use import to include that class and methods in the current working directory.

import java.util.Date

Importing packages in Scala is more flexible than in other languages. We can place import statements anywhere in the code and even hide or rename members of packages when you import them.

Note: Users can either import the package as a whole or some of its member methods, classes, etc.

Example - Import in Scala

Taking the first example of class Animals, we must follow the below syntax in order to import some of the methods or classes of the package.

// imports everything from the package
import animals._
// imports only land/walking animals
import animals.land_animals
// imports only these two selected members
import animals.{land_animal, mammals}
// renaming while importing in Scala
import animals.{land_animals as landAnimals}

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved