Packages and package objects

Just like Java, a package is a special container or object which contains/defines a set of objects, classes, and even packages. Every Scala file has the following automatically imported:

  • java.lang._
  • scala._
  • scala.Predef._

The following is an example for basic imports:

// import only one member of a package
import java.io.File
// Import all members in a specific package
import java.io._
// Import many members in a single import statement
import java.io.{File, IOException, FileNotFoundException}
// Import many members in a multiple import statement
import java.io.File
import java.io.FileNotFoundException
import java.io.IOException

You can even rename a member while importing, and that's to avoid a collision between packages that have the same member name. This method is also called class alias:

import java.util.{List => UtilList}
import java.awt.{List => AwtList}
// In the code, you can use the alias that you have created
val list = new UtilList

As mentioned in Chapter 1, Introduction to Scala, you can also import all the members of a package, but some members are also called member hiding:

import java.io.{File => _, _}

If you tried this in the REPL, it just tells the compiler the full, canonical name of the defined class or object:

package fo.ba
class Fo {
override def toString = "I'm fo.ba.Fo"
}

You can even use the style of defining packages in curly braces. You can have a single package and nested package means package within a package. For example, the following code segment defines a single package named singlePackage consisting of a single class named Test. The Test class, on the other hand, consists of a single method named toString().

package singlePack {
class Test { override def toString = "I am SinglePack.Test" }
}

Now, you can make the packaging nested. In other words, you can have more than one package in a nested way. For example, for the below case, we have two packages, namely NestParentPack and the NestChildPack, each containing their own classes.

package nestParentPack {
class Test { override def toString = "I am NestParentPack.Test" }

package nestChildPack {
class TestChild { override def toString = "I am nestParentPack.nestChildPack.TestChild" }
}
}

Let's create a new object (let's name it MainProgram), in which we'll invoke the methods and classes we just defined:

object MainProgram {
def main(args: Array[String]): Unit = {
println(new nestParentPack.Test())
println(new nestParentPack.nestChildPack.TestChild())
}
}

You will find more examples on the internet that describe sophisticated use cases of packages and package objects. In the next section, we will discuss the Java interoperability of Scala codes.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.12.166.61