Scala Learning (vii)---package and introduction

Source: Internet
Author: User
Tags class manager naming convention

Package and introduction

Summary :

In this article, you will learn how the packages and introduction statements in Scala work. It's more routine and more flexible than Java, whether it's a package or an introduction . The main points of this article include:

1. Packages can also be nested like inner classes

2. Package path is not an absolute path

3. Package declaration chain x.y.z does not automatically turn the intermediate package X and x.y into visible

4. package declarations at the top of the file without braces are valid throughout the file scope

5. Package Objects can hold functions and variables

6. Introduce statements to introduce packages, classes, and objects

7. The introduction statement can appear in any location

8. Introduce statements to rename and hide specific members

9. Java.lang, Scala and predef are always introduced

Package

Scala contains the semantic

Scala's packages are the same as those in Java or the namespaces in C + + : manage names in large programs . For example, thename map can appear in both scala.collection.immutable and Scala. collection.mutable Package without conflict. To access any of them, you can use the fully qualified name SC Ala.collection.immutable.Map or SCALA.COLLECTION.MUTABLE.MAP, you can also use the introduction statement to provide a shorter alias

To add an entry to a package, you can include it in a package statement, such as:

Package COM {

Package Horstmann {

Package Impatient {

Class Employee

.......

}

}

}

This allows the class name employee to access the Com.horstmann.impatient.Employee at any location

The package definition in Scala

Unlike the definition of an object or class, the same package can be defined in multiple files . The preceding code may appear in file Employee.scala, and another file named Manager.scala may contain:

Package COM {

Package Horstmann {

Package Impatient {

Class Manager

.......

}

}

}

This shows that there is no mandatory association between the source file's directory and the package. You don't need to put Employee.scala and Manager.scala in the Com/horstmann/impatient directory.

In other words, you can also contribute content to multiple packages in the same file . The Employee.scala file can contain:

Package COM {

Package Horstmann {

Package Impatient {

Class Employee

.......

}

}

}

package Org {

Package Bigjava {

Class Counter

.......

}

}

Scope rules

Package nesting

In Scala, the scope of the package is more consistent than Java. Scala's packages support nesting as well as other scopes, and you can access the names in the upper scope. For example:

Package COM {

Package Horstmann {

Object Utils {

def percent of (value:double, rate:double) = value*rate/100

..........

}

Package Impatient {

Class Employee

.......

def giveraise (rate:Scala.Double) {

Salary + = utils.percentof(salary,rate)

}

}

}

}

Note the Utils.percentof modifier. The Utils class is defined in the parent package, and the contents of all the parent packages are within scope, so it is not necessary to use com.horstmann.Utils.precentOf.

Package conflicts

However, there is a flaw here. Suppose you have the following code:

Package COM {

Package Horstmann {

Package Impatient {

Class Manager {

Val suboardinates = new Collection.mutable.arraybuffer[employee]

.......

}

}

}

}

Here we use a feature that the Scala package is always introduced. Therefore, the collection package actually points to scala.collection. Now suppose someone joins the following package, possibly in another file:

Package COM {

Package Horstmann {

Package Collection {

.......

}

}

}

The manager class will no longer be compiled. The compiler tried to find the mutable member in the Com.horstmann.collection package without an effect. The manager class is intended to use the collection package in the top-level Scala package, not just any child packages that exist in the accessible scope

Package conflict Scenarios

In Java, this problem does not occur because the package name is always absolute, starting at the top of the package hierarchy. But in Scala, the package name is relative, just like the name of the inner class. Internal classes typically do not encounter this problem because all of the code is in the same file and is controlled directly by the person responsible for the file. But the package is different, and anyone can add content to any package at any time.

One workaround is to use the absolute package name , starting with _root_ , for example:

Val subordinates=new _root_.scala. Collction.mutable.arraybutfer[employee]

Another approach is to use the " inline" package statement , which will be discussed in more detail later

Inline Package Statements

A package statement can contain a "string", or a path segment , for example:

Package Com.horstmann.impatient {//COM and Com.horstmann members are not visible here

Package people {

Class Person

}

}

Such a package statement qualifies the visible members. Now the Com.horstmann.collection package is no longer able to access the collection

Document Top Marking method

In addition to the nested notation We've seen so far, you can use the package statement at the top of the file without curly braces. For example:

Package Com.horstmann.impatient

Package people

Class Person

This is equivalent to

Package Com.horstmann.impatient {

Package people {

Class Person

......

Until the end of the file

}

}

If all the code in the file belongs to the same package: This is also the usual scenario, which is a better practice. Also note that: In the above example, all the contents of the file belong to Com.horstmann.impatient.people, but the contents of the Com.horstmann.impatient package are visible and can be directly referenced

Package Object

A package can contain classes , objects , and attributes , but cannot contain definitions of functions or variables. Unfortunately, this is a limitation of the Java Virtual machine. It is more reasonable to add tool functions or constants to a package instead of a Utils object. The appearance of the package object is precisely to solve this limitation. Each package can have a package object. You need to define it in the parent package, and the name is the same as the child package. For example

Package com.horstmann.impatient

Package Object People {

package people {

class person {

var name=defaultname//The constant

"

}

}

Note DefaultName does not need to add qualifiers because it is in the same package. In other places, this constant can be accessed with com.horstmann.impatient.people.defaultName. Behind the scenes, the package object is compiled into a JVM class with static methods and fields , named Package.class, located under the corresponding package. Corresponds to this example, which is com.horstmann.impatient.people.package, which has a static field defaultname. In the JVM, you can use the package as the class name. It is good practice to use the same naming convention for source files, and you can put the package object in the file Com/horstmann/impatient/people/package.scala. That way, anyone who wants to add a function or variable to a package can easily find the corresponding package object

Package visibility

In Java, a class member that is not declared public, private, or protected is visible in the package that contains the class. In Scala, you can achieve the same effect with modifiers . The following methods are visible in its own package:

Package Com.horstmann.impatient.people

Class Person {

Private[people] def description= "A person with Name" +name

.......

}

You can extend the visibility to the upper-level package:

Private[impatient] def description= "A person with Name" +name

Introduced

The introduction of statements allows you to use shorter names instead of the original longer names. The wording is as follows:

Import Java.awt.Color

In this way, you can write color in the code instead of Java.awt.Color, which is the only purpose of introducing the statement. If you don't mind the long name, you absolutely don't need to use the introduction. You can also introduce all members of a package :

Import java.awt. _

This is the same as a wildcard * in Java. In Scala, * is a valid identifier. You can definitely define a package like com.horstmann.*.people, but please don't do it. You can also introduce all members of a class or object :

Import Java.awt.color._

Val C1 =red//Color.Red

Val C2=decode ("#ff0000")//Color.decode

This is like import static in Java. Java programmers seem to be afraid of this, but such bows are common in Scala. Once you have introduced a package, you can access its child package with a shorter name. For example:

Import Java.awt._

def handler (Evt:event. ActionEvent) {//Java.awt.event.ActionEvent

..........

}

The event package is a member of the java.awt package, so the introduction of the statement takes it into scope

Any place can be declared to introduce

In Scala, an import statement can appear anywhere, not just at the top of the file. The effect of the import statement extends to the end of the block that contains the statement. For example:

Class Manager {

Import Scala.collection.mutable._

Val subordinates = new Arraybuffer[employee]

}

This is a useful feature, especially for the introduction of a wildcard. Introducing a large number of names from multiple sources is always a concern. In fact, some Java programmers do not particularly like the introduction of the wildcard, so that they do not use this feature, but rather let the IDE help them to generate a long list of introduction statements. By placing the introduction where these are needed, you can drastically reduce the potential for name collisions .

Renaming and Hiding methods

Renaming

If you want to seduce Several members of a package , you can use the Picker (selector) like this:

Import Java.awt.Color. {Color,font}

The picker syntax also allows you to rename the selected member:

Import Java.util. {Hashmap=>javahashmap}

Import Scala.collection.mutable._

In this way, Javahashmap is Java.utiI.HashMap, and HashMap corresponds to SCALA.COLLECTION.MUTABLE.HASHMAP.

Hide method

Picker HashMap =>_ hides a member instead of renaming it. This is only useful if you need to introduce other Members:

Import Java.util. {Hashmap=>_,_}

Import Scala.collection.mutable._

Now, HashMap points to Scala.collection.mutable.HashMap, because Java.util.HashMap is hidden.

Implicit introduction

Each Scala program is implicitly starting with the following code:

Import Java.lang._

Import Scala._

Import Predef._

Like Java programs,Java.lang is always introduced. Next, theScala package is introduced, but in a somewhat special way. Unlike all other introductions, this introduction is allowed to overwrite the previous introduction . For example, Scala. StringBuilder cover Java.lang.StringBuilder rather than conflict with it. Finally, the Predef object is introduced. It contains quite a few useful functions, which can also be placed in the Scala package object, but Predef existed before Scala was added to the package object.

Since the Scala package is introduced by default, you don't need to write all of this prefix for packages that start with Scala. For example:

Collection.mutable.HashMap

The code above is as good as the following:

Scala.collection.mutable. HashMap

If you think reading this blog gives you something to gain, you might want to click "recommend" in the lower right corner.
If you want to find my new blog more easily, click on "Follow Me" in the lower left corner.
If you are interested in what my blog is talking about, please keep following my follow-up blog, I am "sunddenly".

This article is copyright to the author and the blog Park, Welcome to reprint, but without the consent of the author must retain this paragraph, and in the article page obvious location to the original link, otherwise reserves the right to pursue legal responsibility.

Scala Learning (vii)---package and introduction

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.