A package is a named compile-time collection of related class, object, trait, and sub-package declarations.
Scala packages are similar in purpose to Java packages and C++ namespaces.
· In Eclipse create a new Scala project called PackageDemo
· In PackageDemo create a new package called library
· In library add a class called Account
In Account.scala we can add sub-packages of the library package:
package library
package banking {
class Account {}
class Transaction { }
class AccountHolder
extends hr.Person { }
}
package hr {
class Person {}
class Employee extends Person {}
class Manager extends Employee
class Benefit {}
}
package business {
import banking._
class Customer extends AccountHolder { }
}
A Scala package cannot contain the declarations of functions in variables. These must be placed in special package objects.
· In Eclipse add a package to library called library.math
· Add a package object to this package
A package object can contain function, value, and variable declarations:
package library // ???
package object math {
val pi = 3.14
def square(x: Double) = x * x
def circleArea(radius: Double) = pi *
square(radius)
}
Here's a test:
println("circle area = " + library.math.circleArea(20))
val smith = new library.banking.AccountHolder()
The scala package contains core types like Int, Float, Array or Option which are accessible in all Scala compilation units without explicit qualification or imports.
Notable packages include:
scala.collection and its sub-packages contain Scala's collections framework
scala.collection.immutable - Immutable, sequential data-structures such as Vector, List, Range, HashMap or HasSet
scala.collection.mutable - Mutable, sequential data-structures such as ArrayBuffer, StringBuilder, HashMap or HashSet
scala.io - Input and output operations
scala.math - Basic math functions and additional numeric types like BigInt and BigDecimal
scala.sys - Interaction with other processes and the operating system
scala.util.matching - Regular expressions
Additional parts of the standard library are shipped as separate libraries. These include:
scala.reflect - Scala's reflection API (scala-reflect.jar)
scala.xml - XML parsing, manipulation, and serialization (scala-xml.jar)
scala.swing - A convenient wrapper around Java's GUI framework called Swing (scala-swing.jar)
scala.util.continuations - Delimited continuations using continuation-passing-style (scala-continuations-library.jar, scala-continuations-plugin.jar)
scala.util.parsing - Parser combinators, including an example implementation of a JSON parser (scala-parser-combinators.jar)
scala.actors - Actor-based concurrency (deprecated and replaced by Akka actors, scala-actors.jar)
In addition, all Java packages can be imported into a Scala program.