Scala/Import
Importation in Scala is a mechanism that enables more direct reference of different entities such as packages, classes, objects, instances, fields and methods.
Import
Any importation is defined using the keyword "import". A simple example of importing an object contained in a package:
package p1 { class A } object B { val x = new p1.A import p1.A val y = new A }
In lines 1-3, a package named "p1" containing a class named "A" is declared. In lines 4-8, an object named "B" is defined. At line 5, a value named "x" is assigned a new instance of class "A" using the full identifier "p1.A" for class "A". At line 6, the keyword "import" is used, followed by the identifier "p1.A". The "import" declaration makes it possible for all following entities in the scope to refer directly to the last part of the identifier in the declaration, here the class "A". In the seventh line, the class "A" is referred to directly without having to use its full identifier.
Entities that can be imported includes members such as fields and methods of objects:
import math.Pi import math.round println("Pi is: " + Pi) //Prints "Pi is: 3.141592653589793". println("Pi rounded is: " + round(Pi)) //Prints "Pi rounded is: 3".
In the first line, the field named "Pi" of object "math" is imported, making it available to entities following the import declaration. In the second line, the method named "round" of object "math" is likewise imported. In the fourth and fifth line, "Pi" and "round" is referred to directly without the normal required identifiers "math.Pi" and "math.round".
The members of instances can also be imported:
class Cube(val a:Double) def volume(cube:Cube) = { import cube.a a*a*a } val cube1 = new Cube(4) println("The volume of cube1 is: " + volume(cube1)) //Prints "The volume of cube1 is: 64.0".
In the first line a class named "Cube" with a value named "a" indicating side-length is declared. In lines 2-5, a method calculating a cube's volume is defined. At line 3, the field "a" of the argument named "cube" is imported, and in line 4 "a" is referred to directly. A new cube is instantiated in line 6, and its volume is printed in line 7.
Packages can also be imported:
package p1.p2 { class A } import p1.p2 val a = new p2.A
In the first 3 lines, two nested packages named "p1" and "p2" are declared, with "p2" containing a class named "A". At the fifth line, "p2" is imported. At the seventh line, "p2" is referred to directly without having to qualify it with "p1.p2".