文档介绍:Scala By Example
DRAFT
December 19, 2007
Martin Odersky
PROGRAMMING METHODS LABORATORY
EPFL
SWITZERLAND
Contents
1 Introduction 1
2 A First Example 3
3 Programming with Actors and Messages 7
4 Expressions and Simple Functions 11
Expressions And Simple Functions . . . . . . . . . . . . . . . . . . . . . . 11
Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Conditional Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Example: Square Roots by Newton’s Method . . . . . . . . . . . . . . . . 15
Nested Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Tail Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
5 First-Class Functions 21
Anonymous Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Currying . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
Example: Finding Fixed Points of Functions . . . . . . . . . . . . . . . . 25
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
Language Elements Seen So Far . . . . . . . . . . . . . . . . . . . . . . . 28
6 Classes and Objects 31
7 Case Classes and Pattern Matching 43
Case Classes and Case Objects . . . . . . . . . . . . . . . . . . . . . . . . 46
Pattern Matching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
8 Generic Types and Methods 51
Type Parameter Bounds . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
Variance Annotations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
iv CONTENTS
Lower Bounds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
Least Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
Tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
Function