Scala教程

专注Scala

Let’s start with a brief look at why you should give Scala a serious look. Then we’ll dive in and write some code.

Why Scala?

Scala is a language that addresses the needs of the modern software developer. It is a statically typed, mixed-paradigm, JVM language with a succinct(简洁的;简明的;紧身的), elegant, and flexible syntax, a sophisticated(复杂的) type system, and idioms that promote scalability from small,interpreted scripts to large, sophisticated applications. That’s a mouthful, so let’s look at each of those ideas in more detail:

A JVM and JavaScript language

Scala exploits(利用) the performance and optimizations(最佳化) of the JVM, as well as the rich ecosystem of tools and libraries built around Java. But it’s not limited to the JVM!Scala.js is an experimental port to JavaScript.

Statically typed

Scala embraces(拥抱) static typing as a tool for creating robust applications. It fixes many of the flaws of Java’s type system and it uses type inference to eliminate much of the typing boilerplate.

Mixed paradigm—object-oriented programming

Scala fully supports object-oriented programming (OOP). Scala improves Java’s object model with the addition of traits, a clean way of implementing types using mixin composition. In Scala, everything really is an object, even numeric types.

Mixed paradigm—functional programming

Scala fully supports functional programming (FP). FP has emerged as the best tool for thinking about problems of concurrency, Big Data, and general code correctness. Immutable values, first-class functions, functions without side effects,“higher-order” functions, and function collections all contribute to concise, powerful, correct code.

A sophisticated type system

Scala extends the type system of Java with more flexible generics and other enhancements to improve code correctness. With type inference, Scala code is often as concise as code in dynamically typed languages.

A succinct, elegant, and flexible syntax

Verbose expressions in Java become concise idioms in Scala. Scala provides several facilities for building domain-specific languages (DSLs), APIs that feel “native” to users.

Scalable—architectures

You can write small, interpreted scripts to large, distributed applications in Scala.Four language mechanisms promote scalable composition of systems: 1) mixin composition using traits; 2) abstract type members and generics; 3) nested classes; and 4) explicit self types.

The name Scala is a contraction(缩写) of the words scalable language. It is pronounced scahlah, like the Italian word for “staircase.” Hence, the two “a”s are pronounced the same.
Scala was started by Martin Odersky in 2001. The first public release was January 20th,2004 (see http://bit.ly/1toEmFE). Martin is a professor in the School of Computer and Communication Sciences at the Ecole Polytechnique Fédérale de Lausanne (EPFL). He spent his graduate years working in the group headed by Niklaus Wirth, of Pascal fame.Martin worked on Pizza, an early functional language on the JVM. He later worked on GJ, a prototype of what later became Generics in Java, along with Philip Wadler, one of the designers of Haskell. Martin was hired by Sun Microsystems to produce the reference implementation of javac, the descendant of which is the Java compiler that ships with the Java Developer Kit (JDK) today.

The Seductions of Scala

The rapid growth of Scala users since the first edition of this book confirms my view that Scala is a language for our time. You can leverage the maturity(成熟) of the JVM, libraries,and production tools, while enjoying state-of-the-art language features with a concise,yet expressive syntax for addressing today’s challenges, such as Big Data, scaling through concurrency, and providing highly available and robust services.
In any field of endeavor, the professionals need sophisticated, powerful tools and techniques. It may take a while to master them, but you make the effort because mastery is the key to your success.
I believe Scala is a language for professional developers. Not all users are professionals,of course, but Scala is the kind of language a professional in our field needs, rich in features, highly performant, expressive for a wide class of problems. It will take you a while to master Scala, but once you do, you won’t feel constrained by your programming language.

What About Java 8?

Java 8 is the most significant update to Java since Java 5 introduced generics. Now we have real anonymous functions, called lambdas. You’ll see why they are so useful in this book. Interfaces have been extended to allow “default” implementations of the methods they declare, making them more usable as composable mixins, like Scala’s traits. These features are arguably the two most valuable improvements that Scala brought to the JVM compared to Java before version 8. So, is there any point in switching?

Scala adds many improvements that Java may never have, due to backward compatibility limitations, or Java may eventually have them but not until years from now. For example,Scala has richer type inference than Java can provide. Scala has powerful pattern matching and for comprehensions that dramatically reduce code size and coupling between types. You’ll see why they are so valuable as we go.

Also, many organizations are understandably cautious about upgrading their JVM in‐frastructure. For them deploying the Java 8 JVM may not be an option for a while. At least those organizations can use Scala now with the Java 6 and 7 JVMs.
Still, if you can use Java 8 you might decide it’s the best path forward for your team.Reading this book will still teach you many useful techniques that you can apply to Java 8 applications. However, I suspect you’ll still find all the additional features of Scala worth the switch.
Okay, let’s get started.

Installing Scala

To get up and running as quickly as possible, this section describes how to install some command-line tools that are all you need to work with the examples in the book.The examples used in this book were written and compiled using Scala version 2.11.2, the latest release at the time of this writing. Most also work unmodified with the previous release, Scala version 2.10.4, because many teams are still using that version.
Scala 2.11 introduced some new features compared to 2.10, but the release mostly focused on general performance improvements and library refactoring. Scala 2.10 introduced a number of new features compared to 2.9. Because your organization may be using any of these versions, we’ll discuss the most important differences as we go.

Here are the steps:

Install Java

Until Scala 2.12 comes along, Java 6, 7, or 8 can be used and it must be installed on your computer (Scala 2.12, which is planned for early 2016, will support Java 8 only). If you need to install Java, go to the Oracle website and follow the instructions to install the full Java Development Kit (JDK).

Install SBT

Install the de facto build tool for Scala, SBT by following the instructions at scalasbt.org. When you are finished, you will have an sbt command that you can run from a Linux or OS X terminal or Windows command window. (Other build tools can be used, as we’ll see in “Other Build Tools” on page 484.)

Get the book’s code examples

Download the code examples as described in “Getting the Code Examples” on page xxiii. Expand the archive somewhere convenient on your computer.

Start SBT

Open a shell or command window and move to the directory where you expanded the code examples. Type the command sbt test, which will download all the dependencies you need, including the Scala compiler and third-party libraries. This will take a while and you’ll need an Internet connection. Then sbt will compile the code and run the unit tests. You’ll see lots of output, ending with a “success” message.If you run the command again, it should finish very quickly because it won’t need to do anything again.

Congratulations! You’re ready to get started. However, you might want to install a few more things that are useful.

For most of the book, we’ll use these tools indirectly through SBT,which downloads the Scala compiler version we want, the standard library, and the required third-party dependencies automatically.

It’s handy to download the Scala tools separately, for those times when you aren’t working in SBT. We’ll run a few of our examples using Scala outside SBT.

Follow the links on the official Scala website to install Scala and optionally, the Scala‐docs, the analog of Javadocs for Scala (in Scala 2.11, the Scala library and Scaladocs have been split into several, smaller libraries). You can also read the Scaladocs online. For your convenience, most mentions of a type in the Scala library will be a link corresponding to a Scaladocs page.

A handy feature of the Scaladocs is a search field above the list of types on the lefthand side. It is very handy for finding a type quickly. Also, the entry for each type has a link to view the corresponding source code in Scala’s GitHub repository, which is a good way to learn how the library was implemented. Look for the link on the line labeled “Source.” It will be near the bottom of the overview discussion for the type.

Any text editor or IDE (integrated development environment) will suffice for working with the examples. You can find Scala support plug-ins for all the major editors and IDEs. For more details, see “Integration with IDEs and Text Editors” on page 485. In general, the community for your favorite editor is your best source of up-to-the-minute information on Scala support.

Using SBT

We’ll learn how SBT works in “SBT, the Standard Build Tool for Scala” on page 482. For now, let’s cover the basics we need to get started.

When you start the sbt command, if you don’t specify a task to run, SBT starts an interactive REPL (Read, Eval, Print, Loop). Let’s try that now and see a few of the available “tasks.”
In the listing that follows, the $ is the shell command prompt (e.g., bash), where you start the sbt command, the > is the default SBT interactive prompt, and the # starts an sbt comment. You can type most of these commands in any order: