This page is no longer maintained — Please continue to the home page at www.scala-lang.org

Text version of Scala Language Specification

16 replies
extempore
Joined: 2008-12-17,
User offline. Last seen 35 weeks 3 days ago.
In case I am not alone in having been driven all the way up the wall and over the nearby cliff in my attempts to cut and paste from the scala specification without devastating the meaning of the paste, I offer the attached plain text version of the scala spec.  It is not perfect, but it is a huge leap forward for me.
It is based on the nightly PDF of today, and is the product of the following successively applied transformations:
 - pdftohtml - htmltotext - me and my text processing friends manually cleaning up a bit until I lost the will to continue
I don't intend to do this again, so the language is frozen right there for all eternity unless someone else wants to make this less of a one-shot thing and/or tell me how to accomplish the same thing on OSX with less manual intervention.

The Scala LanguageSpecificationVersion 2.10DRAFTDecember 21, 2011Martin OderskyPROGRAMMING METHODS LABORATORY EPFLSWITZERLAND

Contents
1 Lexical Syntax   31.1 Identifiers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 1.2 Newline Characters. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51.3 Literals. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81.3.1 Integer Literals. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 1.3.2 Floating Point Literals. . . . . . . . . . . . . . . . . . . . . . . . . 91.3.3 Boolean Literals. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101.3.4 Character Literals. . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 1.3.5 String Literals. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101.3.6 Escape Sequences. . . . . . . . . . . . . . . . . . . . . . . . . . . 121.3.7 Symbol literals. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 1.4 Whitespace and Comments. . . . . . . . . . . . . . . . . . . . . . . . . . 131.5 XML mode. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2 Identifiers, Names and Scopes  15
3 Types  19 3.1 Paths. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203.2 Value Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 3.2.1 Singleton Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213.2.2 Type Projection. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213.2.3 Type Designators. . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 3.2.4 Parameterized Types. . . . . . . . . . . . . . . . . . . . . . . . . . 223.2.5 Tuple Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233.2.6 Annotated Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 3.2.7 Compound Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . 233.2.8 Infix Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253.2.9 Function Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 3.2.10 Existential Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . 263.3 Non-Value Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283.3.1 Method Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 3.3.2 Polymorphic Method Types. . . . . . . . . . . . . . . . . . . . . . 293.3.3 Type Constructors. . . . . . . . . . . . . . . . . . . . . . . . . . . 293.4 Base Types and Member Definitions. . . . . . . . . . . . . . . . . . . . . 29 3.5 Relations between types. . . . . . . . . . . . . . . . . . . . . . . . . . . . 313.5.1 Type Equivalence. . . . . . . . . . . . . . . . . . . . . . . . . . . . 313.5.2 Conformance. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 3.5.3 Weak Conformance. . . . . . . . . . . . . . . . . . . . . . . . . . . 343.6 Volatile Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353.7 Type Erasure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
4 Basic Declarations and Definitions  374.1 Value Declarations and Definitions. . . . . . . . . . . . . . . . . . . . . 384.2 Variable Declarations and Definitions. . . . . . . . . . . . . . . . . . . . 39 4.3 Type Declarations and Type Aliases. . . . . . . . . . . . . . . . . . . . . 414.4 Type Parameters. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 434.5 Variance Annotations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44 4.6 Function Declarations and Definitions. . . . . . . . . . . . . . . . . . . 464.6.1 By-Name Parameters. . . . . . . . . . . . . . . . . . . . . . . . . . 474.6.2 Repeated Parameters. . . . . . . . . . . . . . . . . . . . . . . . . . 48 4.6.3 Procedures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 494.6.4 Method Return Type Inference. . . . . . . . . . . . . . . . . . . . 504.7 Import Clauses. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
5 Classes and Objects  535.1 Templates. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 535.1.1 Constructor Invocations. . . . . . . . . . . . . . . . . . . . . . . . 55 5.1.2 Class Linearization. . . . . . . . . . . . . . . . . . . . . . . . . . . 565.1.3 Class Members. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 575.1.4 Overriding. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58 5.1.5 Inheritance Closure. . . . . . . . . . . . . . . . . . . . . . . . . . 595.1.6 Early Definitions. . . . . . . . . . . . . . . . . . . . . . . . . . . . 605.2 Modifiers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61 5.3 Class Definitions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 645.3.1 Constructor Definitions. . . . . . . . . . . . . . . . . . . . . . . . 665.3.2 Case Classes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67 5.3.3 Traits. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 695.4 Object Definitions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
6 Expressions  73 6.1 Expression Typing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 746.2 Literals. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 746.3 The Null Value. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75 6.4 Designators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 756.5 This and Super . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 766.6 Function Applications. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77 6.6.1 Named and Default Arguments. . . . . . . . . . . . . . . . . . . . 796.7 Method Values. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 806.8 Type Applications. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81 6.9 Tuples. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 816.10 Instance Creation Expressions. . . . . . . . . . . . . . . . . . . . . . . . 816.11 Blocks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82 6.12 Prefix, Infix, and Postfix Operations. . . . . . . . . . . . . . . . . . . . . 836.12.1 Prefix Operations. . . . . . . . . . . . . . . . . . . . . . . . . . . . 846.12.2 Postfix Operations. . . . . . . . . . . . . . . . . . . . . . . . . . . 84 6.12.3 Infix Operations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 846.12.4 Assignment Operators. . . . . . . . . . . . . . . . . . . . . . . . . 856.13 Typed Expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86 6.14 Annotated Expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 866.15 Assignments. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 866.16 Conditional Expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . 88 6.17 While Loop Expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . 886.18 Do Loop Expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 886.19 For Comprehensions and For Loops. . . . . . . . . . . . . . . . . . . . . 89 6.20 Return Expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 916.21 Throw Expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 926.22 Try Expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92 6.23 Anonymous Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 936.24 Constant Expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 956.25 Statements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 6.26 Implicit Conversions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 966.26.1 Value Conversions. . . . . . . . . . . . . . . . . . . . . . . . . . . 966.26.2 Method Conversions. . . . . . . . . . . . . . . . . . . . . . . . . . 97 6.26.3 Overloading Resolution. . . . . . . . . . . . . . . . . . . . . . . . 976.26.4 Local Type Inference. . . . . . . . . . . . . . . . . . . . . . . . . . 1006.26.5 Eta Expansion. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
7 Implicit Parameters and Views  1057.1 The Implicit Modifier. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1057.2 Implicit Parameters. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106 7.3 Views. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1097.4 Context Bounds and View Bounds. . . . . . . . . . . . . . . . . . . . . . 1107.5 Manifests. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
8 Pattern Matching  1138.1 Patterns. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1138.1.1 Variable Patterns. . . . . . . . . . . . . . . . . . . . . . . . . . . . 114 8.1.2 Typed Patterns. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1148.1.3 Pattern Binders. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1148.1.4 Literal Patterns. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 8.1.5 Stable Identifier Patterns. . . . . . . . . . . . . . . . . . . . . . . 1158.1.6 Constructor Patterns. . . . . . . . . . . . . . . . . . . . . . . . . . 1158.1.7 Tuple Patterns. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116 8.1.8 Extractor Patterns. . . . . . . . . . . . . . . . . . . . . . . . . . . . 1168.1.9 Pattern Sequences. . . . . . . . . . . . . . . . . . . . . . . . . . . 1178.1.10 Infix Operation Patterns. . . . . . . . . . . . . . . . . . . . . . . . 117 8.1.11 Pattern Alternatives. . . . . . . . . . . . . . . . . . . . . . . . . . 1188.1.12 XML Patterns. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1188.1.13 Regular Expression Patterns. . . . . . . . . . . . . . . . . . . . . . 118 8.1.14 Irrefutable Patterns. . . . . . . . . . . . . . . . . . . . . . . . . . . 1188.2 Type Patterns. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1198.3 Type Parameter Inference in Patterns. . . . . . . . . . . . . . . . . . . . 119 8.4 Pattern Matching Expressions. . . . . . . . . . . . . . . . . . . . . . . . . 1228.5 Pattern Matching Anonymous Functions. . . . . . . . . . . . . . . . . . 124
9 Top-Level Definitions  127 9.1 Compilation Units. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1279.2 Packagings. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1289.3 Package Objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128 9.4 Package References. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1299.5 Programs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
10 XML expressions and patterns  13110.1 XML expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13110.2 XML patterns. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
11 User-Defined Annotations  135
12 The Scala Standard Library  13912.1 Root Classes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139 12.2 Value Classes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14112.2.1 Numeric Value Types. . . . . . . . . . . . . . . . . . . . . . . . . . 14212.2.2 Class Boolean. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145 12.2.3 Class Unit. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14512.3 Standard Reference Classes. . . . . . . . . . . . . . . . . . . . . . . . . . 14512.3.1 Class String. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146 12.3.2 The Tuple classes. . . . . . . . . . . . . . . . . . . . . . . . . . 14612.3.3 The Function Classes. . . . . . . . . . . . . . . . . . . . . . . 14612.3.4 Class Array. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147 12.4 Class Node. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14912.5 The Predef Object. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15212.5.1 Predefined Implicit Definitions. . . . . . . . . . . . . . . . . . . . 154
A Scala Syntax Summary  159B Change Log  167
1PrefaceScala is a Java-like programming language which unifies object-oriented and func- tional programming. It is a pure object-oriented language in the sense that everyvalue is an object. Types and behavior of objects are described by classes. Classescan be composed using mixin composition. Scala is designed to work seamlessly with two less pure but mainstream object-oriented languages ­ Java and C#.Scala is a functional language in the sense that every function is a value. Nesting offunction definitions and higher-order functions are naturally supported. Scala also supports a general notion of pattern matching which can model the algebraic typesused in many functional languages.Scala has been designed to interoperate seamlessly with Java (an alternative imple- mentation of Scala also works for .NET) . Scala classes can call Java methods, createJava objects, inherit from Java classes and implement Java interfaces. None of thisrequires interface definitions or glue code. Scala has been developed from 2001 in the programming methods laboratory atEPFL. Version 1.0 was released in November 2003. This document describes thesecond version of the language, which was released in March 2006. It acts a refer- ence for the language definition and some core library modules. It is not intended toteach Scala or its concepts; for this there are other documents [Oa04, Ode06, OZ05b,OCRZ03, OZ05a]. Scala has been a collective effort of many people. The design and the implementa-tion of version 1.0 was completed by Philippe Altherr, Vincent Cremet, Gilles Dubo-chet, Burak Emir, Stéphane Micheloud, Nikolay Mihaylov, Michel Schinz, Erik Sten- man, Matthias Zenger, and the author. Iulian Dragos, Gilles Dubochet, PhilippHaller, Sean McDirmid, Lex Spoon, and Geoffrey Washburn joined in the effort todevelop the second version of the language and tools. Gilad Bracha, Craig Cham- bers, Erik Ernst, Matthias Felleisen, Shriram Krishnamurti, Gary Leavens, SebastianManeth, Erik Meijer, Klaus Ostermann, Didier Rémy, Mads Torgersen, and PhilipWadler have shaped the design of the language through lively and inspiring discus- sions and comments on previous versions of this document. The contributors tothe Scala mailing list have also given very useful feedback that helped us improvethe language and its tools. --------------------------------------------------------------------------------------------------------------------------------------------------------------Chapter 1Lexical Syntax Scala programs are written using the Unicode Basic Multilingual Plane (BMP) char-acter set; Unicode supplementary characters are not presently supported. Thischapter defines the two modes of Scala's lexical syntax, the Scala mode and the XML mode. If not otherwise mentioned, the following descriptions of Scala tokens referto Scala mode, and literal characters `c' refer to the ASCII fragment \u0000-\u007F.In Scala mode, Unicode escapes are replaced by the corresponding Unicode charac- ter with the given hexadecimal code.UnicodeEscape ::= \{\\}u{u} hexDigit hexDigit hexDigit hexDigithexDigit::= `0' | · · · | `9' | `A' | · · · | `F' | `a' | · · · | `f' | To construct tokens, characters are distinguished according to the following classes(Unicode general category given in parentheses) :1. Whitespace characters. \u0020 | \u0009 | \u000D | \u000A 2. Letters, which include lower case letters(Ll) , upper case letters(Lu) , title-case letters(Lt) , other letters(Lo) , letter numerals(Nl) and the two characters\u0024 `$' and \u005F `', which both count as upper case letters 3. Digits `0' | . . . | `9'.4. Parentheses `(' | `) ' | `[' | `]' | `{' | `}'.5. Delimiter characters ``' | `'' | `"' | `.' | `;' | `,'. 6. Operator characters.These consist of all printable ASCII characters\u0020-\u007F. which are in none of the sets above, mathematical sym-bols(Sm) and other symbols(So) .------------------------------------------------------------------------------- 4Lexical Syntax  1.1
IdentifiersSyntax:op::=opchar {opchar}varid::=lower idrestplainid ::=upper idrest|varid|opid::=plainid|`\`' stringLit `\`'idrest::= {letter | digit} [`' op]
There are three ways to form an identifier. First, an identifier can start witha letter which can be followed by an arbitrary sequence of letters and digits. This may be followed by underscore `' characters and another string composed ofeither letters and digits or of operator characters. Second, an identifier canstart with an operator character followed by an arbitrary sequence of operator characters. The preceding two forms are called plain identifiers. Finally, anidentifier may also be formed by an arbitrary string between back-quotes (hostsystems may impose some restrictions on which strings are legal for identifiers.)
The identifier then is composed of all characters excluding the backquotesthemselves. As usual, a longest match rule applies. For instance, the stringbigbob++=`def` decomposes into the three identifiers bigbob, ++=, and def. The rules for pattern matching further distinguish between variable identifiers,which start with a lower case letter, and constant identifiers, which do not.The `$' character is reserved for compiler-synthesized identifiers. User programs should not define identifiers which contain `$' characters. Thefollowing names are reserved words instead of being members of the syntacticclass id of lexical identifiers.
  abstract case catch class def do else extends false final finally for  forSome if implicit import lazy match new null object override package  private protected return sealed super this throw trait try true type val   var while with yield _ : = => <- <: <% >: # @
The Unicode operators \u21D2 `' and \u2190 `', which have the ASCII equiva-------------------------------------------------------------------------------- 1.2 Newline Characters5lents `=>' and `<-', are also reserved.Example 1.1.1 Here are examples of identifiers:xObjectmaxIndexp2p empty?+`yield`
ydotproduct*_systemMAXLEN_Example 1.1.2 Backquote-enclosed strings are a solution when one needs to ac- cess Java identifiers that are reserved words in Scala. For instance, the statementThread.yield() is illegal, since yield is a reserved word in Scala. However, here's awork-around:Thread.`yield`() 1.2Newline CharactersSyntax:semi ::= `;' |nl {nl}Scala is a line-oriented language where statements may be terminated by semi-colons or newlines. A newline in a Scala source text is treated as the special token "nl" if the three following criteria are satisfied:1. The token immediately preceding the newline can terminate a statement.2. The token immediately following the newline can begin a statement. 3. The token appears in a region where newlines are enabled.The tokens that can terminate a statement are: literals, identifiers and the followingdelimiters and reserved words:
  this null true false return type <xml-start> _ ) ] }
The tokens that can begin a statement are all Scala tokens except the following de-limiters and reserved words:
  catch else extends finally forSome match with yield , . ; : = => <- <:  <% >: # [ ) ] }
A case token can begin a statement only if followed by a class or object token. Newlines are enabled in:-------------------------------------------------------------------------------6Lexical Syntax1. all of a Scala source file, except for nested regions where newlines are disabled, and2. the interval between matching { and } brace tokens, except for nested regionswhere newlines are disabled.Newlines are disabled in:1. the interval between matching ( and ) parenthesis tokens, except for nested regions where newlines are enabled, and2. the interval between matching [ and ] bracket tokens, except for nested re-gions where newlines are enabled.3. The interval between a case token and its matching => token, except for nested regions where newlines are enabled.4. Any regions analyzed in XML mode (§1.5) .Note that the brace characters of {...} escapes in XML and string literals are nottokens, and therefore do not enclose a region where newlines are enabled. Normally, only a single nl token is inserted between two consecutive non-newlinetokens which are on different lines, even if there are multiple lines between the twotokens. However, if two tokens are separated by at least one completely blank line (i.e a line which contains no printable characters) , then two nl tokens are inserted.The Scala grammar (given in full in Appendix A) contains productions where op-tional nl tokens, but not semicolons, are accepted. This has the effect that a new- line in one of these positions does not terminate an expression or statement. Thesepositions can be summarized as follows:Multiple newline tokens are accepted in the following places (note that a semicolon in place of the newline would be illegal in every one of these cases) :­ between the condition of an conditional expression (§6.16) or while loop(§6.17) and the next following expression, ­ between the enumerators of a for-comprehension (§6.19) and the next follow-ing expression, and­ after the initial type keyword in a type definition or declaration (§4.3) .A single new line token is accepted ­ in front of an opening brace "{", if that brace is a legal continuation of thecurrent statement or expression,­ after an infix operator, if the first token on the next line can start an expression (§6.12) ,-------------------------------------------------------------------------------1.2 Newline Characters7­ in front of a parameter clause (§4.6) ,and­ after an annotation (§11) . Example 1.2.1 The following code contains four well-formed statements, each ontwo lines. The newline tokens between the two lines are not treated as statementseparators.if (x > 0) x = x - 1while (x > 0)x= x / 2for (x <- 1 to 10)println(x)typeIntList = List[Int]Example 1.2.2 The following code designates an anonymous class new Iterator[Int]{private var x = 0def hasNext = truedef next = { x += 1; x }}With an additional newline character, the same code is interpreted as an object cre- ation followed by a local block:new Iterator[Int]{private var x = 0def hasNext = truedef next = { x += 1; x }}Example 1.2.3 The following code designates a single expression: x < 0 ||x > 10With an additional newline character, the same code is interpreted as two expres-sions:------------------------------------------------------------------------------- 8Lexical Syntaxx < 0 ||x > 10Example 1.2.4 The following code designates a single, curried function definition:def func(x: Int)(y: Int) = x + y With an additional newline character, the same code is interpreted as an abstractfunction definition and a syntactically illegal statement:def func(x: Int)(y: Int) = x + yExample 1.2.5 The following code designates an attributed definition: @serializableprotected class Data { ... }With an additional newline character, the same code is interpreted as an attributeand a separate statement (which is syntactically illegal) . @serializableprotected class Data { ... }1.3LiteralsThere are literals for integer numbers, floating point numbers, characters, booleans,symbols, strings. The syntax of these literals is in each case as in Java. Syntax:Literal::=[`-'] integerLiteral|[`-'] floatingPointLiteral|booleanLiteral|characterLiteral| stringLiteral|symbolLiteral|`null'-------------------------------------------------------------------------------1.3 Literals9 1.3.1 Integer LiteralsSyntax:integerLiteral::=(decimalNumeral | hexNumeral | octalNumeral) [`L' | `l']decimalNumeral::=`0' | nonZeroDigit {digit} hexNumeral::=`0' `x' hexDigit {hexDigit}octalNumeral::=`0' octalDigit {octalDigit}digit::=`0' | nonZeroDigit nonZeroDigit::=`1' | · · · | `9'octalDigit::=`0' | · · · | `7'Integer literals are usually of type Int, or of type Long when followed by a L or l suffix. Values of type Int are all integer numbers between -231 and 231 - 1, inclu-sive. Values of type Long are all integer numbers between -263 and 263 -1, inclusive.A compile-time error occurs if an integer literal denotes a number outside these ranges.However, if the expected type pt (§6.1) of a literal in an expression is either Byte,Short, or Char and the integer number fits in the numeric range defined by the type,then the number is converted to type pt and the literal's type is pt. The numeric ranges given by these types are:Byte-27 to 27 - 1Short-215 to 215 - 1Char0 to 216 - 1Example 1.3.1 Here are some integer literals: 0210xFFFFFFFF0777L1.3.2 Floating Point LiteralsSyntax:floatingPointLiteral::=digit {digit} `.' {digit} [exponentPart] [floatType] |`.' digit {digit} [exponentPart] [floatType]|digit {digit} exponentPart [floatType]|digit {digit} [exponentPart] floatTypeexponentPart ::=(`E' | `e') [`+' | `-'] digit {digit}floatType::=`F' | `f' | `D' | `d'Floating point literals are of type Float when followed by a floating point type suffix F or f, and are of type Double otherwise. The type Float consists of all IEEE 754 32-bit single-precision binary floating point values, whereas the type Double consistsof all IEEE 754 64-bit double-precision binary floating point values. -------------------------------------------------------------------------------10Lexical SyntaxIf a floating point literal in a program is followed by a token starting with a letter, there must be at least one intervening whitespace character between the two to-kens.Example 1.3.2 Here are some floating point literals:0.01e30f3.14159f 1.0e-100.1Example 1.3.3 The phrase `1.toString' parses as three different tokens: `1', `.',and `toString'. On the other hand, if a space is inserted after the period, the phrase `1. toString' parses as the floating point literal `1.' followed by the iden-tifier `toString'.1.3.3 Boolean LiteralsSyntax:booleanLiteral::= `true' | `false'The boolean literals true and false are members of type Boolean.1.3.4 Character LiteralsSyntax:characterLiteral::=`\'' printableChar `\'' |`\'' charEscapeSeq `\''A character literal is a single character enclosed in quotes. The character is either aprintable unicode character or is described by an escape sequence (§1.3.6) . Example 1.3.4 Here are some character literals:'a''\u0041''\n''\t'Note that `\u000A' is not a valid character literal because Unicode conversion is done before literal parsing and the Unicode character \u000A (line feed) is not a printablecharacter. One can use instead the escape sequence `\n' or the octal escape `\12'(§1.3.6) . 1.3.5 String LiteralsSyntax:stringLiteral::=`\"' {stringElement} `\"'stringElement::=printableCharNoDoubleQuote| charEscapeSeq-------------------------------------------------------------------------------1.3 Literals11A string literal is a sequence of characters in double quotes. The characters are ei- ther printable unicode character or are described by escape sequences (§1.3.6) .Ifthe string literal contains a double quote character, it must be escaped, i.e. \". Thevalue of a string literal is an instance of class String. Example 1.3.5 Here are some string literals:"Hello,\nWorld!""This string contains a \" character."Multi-Line String LiteralsSyntax:stringLiteral ::=`"""' multiLineChars `"""'multiLineChars::={['"'] ['"'] charNoDoubleQuote} {`"'}A multi-line string literal is a sequence of characters enclosed in triple quotes """ ... """. The sequence of characters is arbitrary, except that it may containthree or more consuctive quote characters only at the very end. Characters mustnot necessarily be printable; newlines or other control characters are also permit- ted. Unicode escapes work as everywhere else, but none of the escape sequences in(§1.3.6) is interpreted.Example 1.3.6 Here is a multi-line string literal:"""the present string spans threelines."""This would produce the string:the present stringspans threelines.The Scala library contains a utility method stripMargin which can be used to strip leading whitespace from multi-line strings. The expression"""the present string|spans three|lines.""".stripMarginevaluates tothe present string -------------------------------------------------------------------------------12Lexical Syntaxspans threelines.Method stripMargin is defined in class scala.collection.immutable.StringLike. Because there is a predefined implicit conversion (§6.26) from String toStringLike, the method is applicable to all strings.1.3.6 Escape SequencesThe following escape sequences are recognized in character and string literals.     \b    \u0008: backspace BS    \t    \u0009: horizontal tab HT    \n    \u000a: linefeed LF    \f    \u000c: form feed FF    \r     \u000d: carriage return CR    \"    \u0022: double quote "    \'    \u0027: single quote '    \\    \u005c: backslash \ A character with Unicode between 0 and 255 may also be represented by an octalescape, i.e. a backslash `\' followed by a sequence of up to three octal characters.It is a compile time error if a backslash character in a character or string literal does not start a valid escape sequence.1.3.7 Symbol literalsSyntax:symbolLiteral::=`'' plainidA symbol literal 'x is a shorthand for the expression scala.Symbol("x") . Symbol is a case class (§5.3.2) ,which is defined as follows.package scalafinal case class Symbol private (name: String) {override def toString: String = "'" + name} The apply method of Symbol's companion object caches weak references to Symbols,thus ensuring that identical symbol literals are equivalent with respect to referenceequality.------------------------------------------------------------------------------- 1.4 Whitespace and Comments131.4Whitespace and CommentsTokens may be separated by whitespace characters and/or comments. Commentscome in two forms:A single-line comment is a sequence of characters which starts with // and extends to the end of the line.A multi-line comment is a sequence of characters between /* and */. Multi-linecomments may be nested, but are required to be properly nested. Therefore, a com-ment like /* /* */ will be rejected as having an unterminated comment. 1.5XML modeIn order to allow literal inclusion of XML fragments, lexical analysis switches fromScala mode to XML mode when encountering an opening angle bracket '<' in the following circumstance: The '<' must be preceded either by whitespace, an openingparenthesis or an opening brace and immediately followed by a character startingan XML name. Syntax:( whitespace | `(' | `{' ) `<' (XNameStart | `!' | `?')XNameStart ::= `' | BaseChar | Ideographic (as in W3C XML, but without `:'The scanner switches from XML mode to Scala mode if either · the XML expression or the XML pattern started by the initial '<' has been suc-cessfully parsed, or if· the parser encounters an embedded Scala expression or pattern and forces the Scanner back to normal mode, until the Scala expression or pattern is suc-cessfully parsed. In this case, since code and XML fragments can be nested,the parser has to maintain a stack that reflects the nesting of XML and Scala expressions adequately.Note that no Scala tokens are constructed in XML mode, and that comments areinterpreted as text.Example 1.5.1 The following value definition uses an XML literal with two embed- ded Scala expressionsval b = <book><title>The Scala Language Specification</title><version>{scalaBook.version}</version><authors>{scalaBook.authors.mkList("", ", ", "") }</authors> </book>--------------------------------------------------------------------------------------------------------------------------------------------------------------Chapter 2 Identifiers, Names and ScopesNames in Scala identify types, values, methods, and classes which are collectivelycalled entities. Names are introduced by local definitions and declarations (§4) ,in- heritance (§5.1.3) ,import clauses (§4.7) ,or package clauses (§9.2) which are collec-tively called bindings.Bindings of different kinds have a precedence defined on them:1. Definitions and declarations that are local, inherited, or made available by a package clause in the same compilation unit where the definition occurs havehighest precedence.2. Explicit imports have next highest precedence.3. Wildcard imports have next highest precedence. 4. Definitions made available by a package clause not in the compilation unitwhere the definition occurs have lowest precedence.There are two different name spaces, one for types (§3) and one for terms (§6) .The same name may designate a type and a term, depending on the context where thename is used.A binding has a scope in which the entity defined by a single name can be accessedusing a simple name. Scopes are nested. A binding in some inner scope shadows bindings of lower precedence in the same scope as well as bindings of the same orlower precedence in outer scopes.Note that shadowing is only a partial order. In a situation likeval x = 1; { import p.x;x }-------------------------------------------------------------------------------16Identifiers, Names and Scopesneither binding of x shadows the other. Consequently, the reference to x in the third line above would be ambiguous.A reference to an unqualified (type- or term-) identifier x is bound by the uniquebinding, which· defines an entity with name x in the same namespace as the identifier, and · shadows all other bindings that define entities with name x in that names-pace.It is an error if no such binding exists. If x is bound by an import clause, then thesimple name x is taken to be equivalent to the qualified name to which x is mapped by the import clause. If x is bound by a definition or declaration, then x refers tothe entity introduced by that binding. In that case, the type of x is the type of thereferenced entity. Example 2.0.2 Assume the following two definitions of a objects named X in pack-ages P and Q.package P {object X { val x = 1; val y = 2 }}package Q {object X { val x = true; val y = "" } }The following program illustrates different kinds of bindings and precedences be-tween them.
    package P {      // `X' bound by package clause       import Console._      // `println' bound by wildcard import      object A {        println("L4: "+X)        // `X' refers to `P.X' here        object B {           import Q._          // `X' bound by wildcard import          println("L7: "+X)          // `X' refers to `Q.X' here          import X._           // `x' and `y' bound by wildcard import          println("L8: "+x)          // `x' refers to `Q.X.x' here          object C {            val x = 3             // `x' bound by local definition            println("L12: "+x)            // `x' refers to constant `3' here            { import Q.X._              // `x' and `y' bound by wildcard import               //              println("L14: "+x)              // reference to `x' is ambiguous here              import X.y              // `y' bound by explicit import               println("L16: "+y)              // `y' refers to `Q.X.y' here              -------------------------------------------------------------------------------               17              { val x = "abc"                // `x' bound by local definition                import P.X._                // `x' and `y' bound by wildcard import                 //                println("L19: "+y) // reference to `y' is ambiguous here                println("L20: "+x) // `x' refers to string ``abc'' here               }            }          }        }      }    }
A reference to a qualified (type- or term-) identifier e.x refers to the member of the type T of e which has the name x in the same namespace as the identifier. It isan error if T is not a value type (§3.2) .The type of e.x is the member type of thereferenced entity in T . --------------------------------------------------------------------------------------------------------------------------------------------------------------Chapter 3TypesSyntax: Type::=FunctionArgTypes `=>' Type|InfixType [ExistentialClause]FunctionArgTypes::= InfixType| `(' [ ParamType {`,' ParamType } ] `) ' ExistentialClause ::=`forSome' `{' ExistentialDcl {semi ExistentialDcl} `}'ExistentialDcl::=`type' TypeDcl|`val' ValDcl InfixType::=CompoundType {id [nl] CompoundType}CompoundType::=AnnotType {`with' AnnotType} [Refinement]|RefinementAnnotType ::=SimpleType {Annotation}SimpleType::=SimpleType TypeArgs|SimpleType `#' id|StableId|Path `.' `type' |`(' Types ') 'TypeArgs::=`[' Types `]'Types::=Type {`,' Type}We distinguish between first-order types and type constructors, which take type pa- rameters and yield types. A subset of first-order types called value types representssets of (first-class) values. Value types are either concrete or abstract.Every concrete value type can be represented as a class type, i.e. a type designator (§3.2.3) that refers to a a class or a trait1(§5.3) ,or as a compound type (§3.2.7) rep-resenting an intersection of types, possibly with a refinement (§3.2.7) that furtherconstrains the types of its members. Abstract value types are introduced by type 1We assume that objects and packages also implicitly define a class (of the same name as theobject or package, but inaccessible to user programs) .------------------------------------------------------------------------------- 20Typesparameters (§4.4) and abstract type bindings (§4.3) .Parentheses in types can beused for grouping.Non-value types capture properties of identifiers that are not values (§3.3) .For ex- ample, a type constructor (§3.3.3) does not directly specify a type of values. How-ever, when a type constructor is applied to the correct type arguments, it yields afirst-order type, which may be a value type. Non-value types are expressed indirectly in Scala. E.g., a method type is describedby writing down a method signature, which in itself is not a real type, although itgives rise to a corresponding method type (§3.3.1) .Type constructors are another example, as one can write type Swap[m[, ], a,b] = m[b, a], but there is nosyntax to write the corresponding anonymous type function directly.3.1PathsSyntax:Path ::=StableId|[id `.'] thisStableId::=id|Path `.' id|[id '.'] `super' [ClassQualifier] `.' id ClassQualifier::= `[' id `]'Paths are not types themselves, but they can be a part of named types and in thatfunction form a central role in Scala's type system. A path is one of the following.· The empty path (which cannot be written explicitly in user programs) .· C .this, where C references a class. The path this is taken as a shorthand forC .this where C is the name of the class directly enclosing the reference. · p.x where p is a path and x is a stable member of p. Stable members arepackages or members introduced by object definitions or by value definitionsof non-volatile types (§3.6) .· C .super.x or C .super[M ].x where C references a class and x references a stable member of the super class or designated parent class M of C . The prefixsuper is taken as a shorthand for C .super where C is the name of the classdirectly enclosing the reference. A stable identifier is a path which ends in an identifier.-------------------------------------------------------------------------------3.2 Value Types213.2Value Types Every value in Scala has a type which is of one of the following forms.3.2.1 Singleton TypesSyntax:SimpleType::=Path `.' typeA singleton type is of the form p.type, where p is a path pointing to a value expected to conform (§6.1) to scala.AnyRef. The type denotes the set of values consisting ofnull and the value denoted by p.A stable type is either a singleton type or a type which is declared to be a subtype of trait scala.Singleton.3.2.2 Type ProjectionSyntax:SimpleType::=SimpleType `#' idA type projection T #x references the type member named x of type T . 3.2.3 Type DesignatorsSyntax:SimpleType::=StableIdA type designator refers to a named value type. It can be simple or qualified. Allsuch type designators are shorthands for type projections. Specifically, the unqualified type name t where t is bound in some class, object, orpackage C is taken as a shorthand for C .this.type#t . If t is not bound in a class,object, or package, then t is taken as a shorthand for .type#t . A qualified type designator has the form p.t where p is a path (§3.1) and t is a typename. Such a type designator is equivalent to the type projection p.type#t .Example 3.2.1 Some type designators and their expansions are listed below. We assume a local type parameter t , a value maintable with a type member Node andthe standard class scala.Int,t.type#tIntscala.type#Intscala.Int scala.type#Intdata.maintable.Nodedata.maintable.type#Node-------------------------------------------------------------------------------22Types3.2.4 Parameterized Types Syntax:SimpleType::=SimpleType TypeArgsTypeArgs::=`[' Types `]'A parameterized type T [U1, ..., Un] consists of a type designator T and type param- eters U1, ..., Un where n 1. T must refer to a type constructor which takes n typeparameters a1, ..., an.Say the type parameters have lower bounds L1, ..., Ln and upper bounds U1, ..., Un. The parameterized type is well-formed if each actual type parameter conforms to itsbounds, i.e. Li <: Ti <: Ui where is the substitution [a1 := T1, ..., an := Tn].Example 3.2.2 Given the partial type definitions:
    class TreeMap[A <: Comparable[A], B] { . . . }    class List[A] { . . . }    class I extends Comparable[I] { . . . }    class F[M[], X] { . . . }    class S[K <: String] { . . . }     class G[M[ Z <: I ], I] { . . . }
the following parameterized types are well formed:
    TreeMap[I, String]    List[I]    List[List[Boolean]]     F[List, Int]    G[S, String]
Example 3.2.3 Given the type definitions of Example 3.2.2,the following types areill-formed:TreeMap[I]// illegal: wrong number of parameters TreeMap[List[I], Int] // illegal: type parameter not within boundF[Int, Boolean]// illegal: Int is not a type constructorF[TreeMap, Int]// illegal: TreeMap takes two parameters, //F expects a constructor taking oneG[S, Int]// illegal: S constrains its parameter to//conform to String,// G expects type constructor with a parameter //that conforms to Int-------------------------------------------------------------------------------3.2 Value Types233.2.5 Tuple TypesSyntax: SimpleType::=`(' Types ') 'A tuple type (T1, ..., Tn) is an alias for the class scala.Tuplen[T1, ..., Tn], wheren 2.Tuple classes are case classes whose fields can be accessed using selectors 1, ..., n. Their functionality is abstracted in a corresponding Product trait. The n-ary tupleclass and product trait are defined at least as follows in the standard Scala library(they might also add other methods and implement other traits) . case class Tuplen[+T1, ..., +Tn](1: T1, ..., n: Tn)extends Productn[T1, ..., Tn] {}trait Productn[+T1, +T2, +Tn] {override def productArity = ndef 1: T1... def n:Tn}3.2.6 Annotated TypesSyntax:AnnotType::=SimpleType {Annotation}An annotated type T a1 ... an attaches annotations a1, ..., an to the type T (§11) . Example 3.2.4 The following type adds the @suspendable@ annotation to the typeString:String @suspendable3.2.7 Compound TypesSyntax:CompoundType::= AnnotType {`with' AnnotType} [Refinement]|RefinementRefinement::=[nl] `{' RefineStat {semi RefineStat} `}'RefineStat::= Dcl|`type' TypeDef|-------------------------------------------------------------------------------24TypesA compound type T1 with ... with Tn {R } represents objects with members as given in the component types T1, ..., Tn and the refinement {R }. A refinement {R }contains declarations and type definitions. If a declaration or definition overrides adeclaration or definition in one of the component types T1, ..., Tn, the usual rules for overriding (§5.1.4) apply; otherwise the declaration or definition is said to be"structural"2.Within a method declaration in a structural refinement, the type of any value pa- rameter may only refer to type parameters or abstract types that are contained in-side the refinement. That is, it must refer either to a type parameter of the methoditself, or to a type definition within the refinement. This restriction does not apply to the function's result type.If no refinement is given, the empty refinement is implicitly added, i.e.T1 with ... with Tn is a shorthand for T1 with ... with Tn {}.A compound type may also consist of just a refinement {R } with no preceding component types. Such a type is equivalent to AnyRef{R }.Example 3.2.5 The following example shows how to declare and use a functionwhich parameter's type contains a refinement with structural declarations. case class Bird (val name: String) extends Object {def fly(height: Int) = ......}case class Plane (val callsign: String) extends Object {def fly(height: Int) = ... ...}def takeoff(runway: Int,r: { val callsign: String; def fly(height: Int) }) = {tower.print(r.callsign + " requests take-off on runway " + runway) tower.read(r.callsign + " is clear for take-off")r.fly(1000)}val bird = new Bird("Polly the parrot") { val callsign = name }val a380 = new Plane("TZ-987") takeoff(42, bird)takeoff(89, a380)Although Bird and Plane do not share any parent class other than Object, theparameter r of function takeoff is defined using a refinement with structural dec- larations to accept any object that declares a value callsign and a fly function.2A reference to a structurally defined member (method call or access to a value or variable) maygenerate binary code that is significantly slower than an equivalent code to a non-structural member. -------------------------------------------------------------------------------3.2 Value Types253.2.8 Infix TypesSyntax:InfixType::=CompoundType {id [nl] CompoundType} An infix type T1 op T2 consists of an infix operator op which gets applied to twotype operands T1 and T2. The type is equivalent to the type application op[T1,T2].The infix operator op may be an arbitrary identifier, except for *, which is reserved as a postfix modifier denoting a repeated parameter type (§4.6.2) .All type infix operators have the same precedence; parentheses have to be used forgrouping. The associativity (§6.12) of a type operator is determined as for term op- erators: type operators ending in a colon `:' are right-associative; all other operatorsare left-associative.In a sequence of consecutive type infix operations t0 op1 t1 op2 ...opn tn, all opera- tors op1, ..., opn must have the same associativity. If they are all left-associative, thesequence is interpreted as (. . . (t0 op1 t1) op2 ...) opn tn, otherwise it is interpreted ast0 op1 (t1 op2 (...opn tn) ...) . 3.2.9 Function TypesSyntax:Type::=FunctionArgs `=>' TypeFunctionArgs::=InfixType|`(' [ ParamType {`,' ParamType } ] `) ' The type (T1, ..., Tn) => U represents the set of function values that take argu-ments of types T1, ..., Tn and yield results of type U . In the case of exactly oneargument type T => U is a shorthand for (T ) => U . An argument type of the form => T represents a call-by-name parameter (§4.6.1) of type T .Function types associate to the right, e.g.S => T => Uis the same asS => (T => U ) . Function types are shorthands for class types that define apply functions. Specif-ically, the n-ary function type (T1, ..., Tn) => U is a shorthand for the class typeFunctionn[T1, . . . , Tn,U ]. Such class types are defined in the Scala library for n between 0 and 9 as follows.package scalatrait Functionn[-T1, . . . , -Tn, +R] {def apply(x1: T1, . . . , xn: Tn) : Roverride def toString = "<function>" }Hence, function types are covariant (§4.5) in their result type and contravariant in-------------------------------------------------------------------------------26Types their argument types.3.2.10 Existential TypesSyntax:Type::= InfixType ExistentialClausesExistentialClauses ::= `forSome' `{' ExistentialDcl{semi ExistentialDcl} `}' ExistentialDcl::= `type' TypeDcl|`val' ValDclAn existential type has the form T forSome {Q } where Q is a sequence of typedeclarations §4.3.Let t1[tps1] >: L1 <: U1, ..., tn[tpsn] >: Ln <: Un be the types de- clared in Q (any of the type parameter sections [tpsi ] might be missing) . The scopeof each type ti includes the type T and the existential clause Q. The type variablesti are said to be bound in the type T forSome {Q }. Type variables which occur in a type T but which are not bound in T are said to be free in T .A type instance of T forSome {Q } is a type T where is a substitution overt1, ..., tn such that, for each i , Li <: ti <: Ui . The set of values denoted by the existential type T forSome {Q } is the union of the set of values of all its type in-stances.A skolemization of T forSome {Q } is a type instance T , where is the substitu-tion [t /t is a fresh abstract type with lower bound L11, . . . , tn /tn ] and each tii andupper bound Ui .Simplification RulesExistential types obey the following four equivalences: 1. Multiple for-clauses in an existential type can be merged.E.g.,T forSome {Q } forSome {Q } is equivalent to T forSome {Q ;Q }.2. Unused quantifications can be dropped. E.g., T forSome {Q ;Q } where none of the types defined in Q are referred to by T or Q, is equivalent toT forSome {Q }.3. An empty quantification can be dropped. E.g., T forSome { } is equivalentto T .4. An existential type T forSome {Q }where Q contains a clausetype t [tps] >: L <: U is equivalent to the typeT forSome {Q }whereT results from T by replacing every covariant occurrence (§4.5) of t in T by U and by replacing every contravariant occurrence of t in T by L.-------------------------------------------------------------------------------3.2 Value Types27Existential Quantification over Values As a syntactic convenience,the bindings clause in an existential typemayalsocontainvaluedeclarationsval x: T .Anexistential typeT forSome { Q; val x: S ;Q }is treated as a shorthand for the typeT forSome { Q; type t <: S with Singleton; Q }, where t is a fresh typename and T results from T by replacing every occurrence of x.type with t . Placeholder Syntax for Existential TypesSyntax:WildcardType::=`' TypeBoundsScala supports a placeholder syntax for existential types. A wildcard type is of the form _ >: L <:U . Both bound clauses may be omitted. If a lower bound clause >: Lis missing, >: scala.Nothing is assumed. If an upper bound clause <:U is miss-ing, <: scala.Any is assumed. A wildcard type is a shorthand for an existentially quantified type variable, where the existential quantification is implicit.A wildcard type must appear as type argument of a parameterized type. Let T =p.c[targs, T, targs ] be a parameterized type where targs, targs may be empty and T is a wildcard type _ >: L <:U . Then T is equivalent to the existential typep.c[targs, t , targs ] forSome { type t >: L <: U }where t is some fresh type variable. Wildcard types may also appear as parts of infix types (§3.2.8) ,function types (§3.2.9) ,or tuple types (§3.2.5) .Their expansion isthen the expansion in the equivalent parameterized type.Example 3.2.6 Assume the class definitionsclass Ref[T] abstract class Outer { type T } .Here are some examples of existential types:Ref[T] forSome { type T <: java.lang.Number }Ref[x.T] forSome { val x: Outer }Ref[xtype # T] forSome { type xtype <: Outer with Singleton } The last two types in this list are equivalent. An alternative formulation of the firsttype above using wildcard syntax is:Ref[_ <: java.lang.Number]Example 3.2.7 The type List[List[]] is equivalent to the existential type -------------------------------------------------------------------------------28TypesList[List[t] forSome { type t }] .Example 3.2.8 Assume a covariant typeclass List[+T] The typeList[T] forSome { type T <: java.lang.Number }is equivalent (by simplification rule 4 above) toList[java.lang.Number] forSome { type T <: java.lang.Number }which is in turn equivalent (by simplification rules 2 and 3 above) to List[java.lang.Number].3.3Non-Value TypesThe types explained in the following do not denote sets of values, nor do they appearexplicitly in programs. They are introduced in this report as the internal types of defined identifiers.3.3.1 Method TypesA method type is denoted internally as (Ps) U , where (Ps) is a sequence of parameternames and types (p1 : T1, ..., pn : Tn) for some n 0 and U is a (value or method) type. This type represents named methods that take arguments named p1, ..., pnof types T1, ..., Tn and that return a result of type U .Method types associate to the right: (Ps1) (Ps2) U is treated as (Ps1) ((Ps2) U ) . A special case are types of methods without any parameters. They are written here=> T. Parameterless methods name expressions that are re-evaluated each time theparameterless method name is referenced. Method types do not exist as types of values. If a method name is used as a value, itstype is implicitly converted to a corresponding function type (§6.26) .Example 3.3.1 The declarations def a: Intdef b (x: Int) : Booleandef c (x: Int) (y: String, z: String) : Stringproduce the typings------------------------------------------------------------------------------- 3.4 Base Types and Member Definitions29a: => Intb: (Int) Booleanc: (Int) (String, String) String3.3.2 Polymorphic Method TypesA polymorphic method type is denoted internally as [tps ]T where [tps ] is a type parameter section [a1 >: L1 <: U1, ..., an >: Ln <: Un] for some n 0 and Tis a (value or method) type. This type represents named methods that take typearguments S1, ..., Sn which conform (§3.2.4) to the lower bounds L1, ..., Ln and the upper bounds U1, ..., Un and that yield results of type T .Example 3.3.2 The declarationsdef empty[A]: List[A]def union[A <: Comparable[A]] (x: Set[A], xs: Set[A]) : Set[A] produce the typingsempty : [A >: Nothing <: Any] List[A]union : [A >: Nothing <: Comparable[A]] (x: Set[A], xs: Set[A]) Set[A].3.3.3 Type Constructors A type constructor is represented internally much like a polymorphic method type.[± a1 >: L1 <: U1, . . . , ±an >: Ln <: Un] T represents a type that is expectedby a type constructor parameter (§4.4) or an abstract type constructor binding (§4.3) with the corresponding type parameter clause.Example 3.3.3 Consider this fragment of the Iterable[+X] class:trait Iterable[+X] {def flatMap[newType[+X] <: Iterable[X], S](f: X => newType[S]) : newType[S] }Conceptually, the type constructor Iterable is a name for the anonymous type[+X] Iterable[X], which may be passed to the newType type constructor param-eter in flatMap.3.4 Base Types and Member DefinitionsTypes of class members depend on the way the members are referenced. Centralhere are three notions, namely:------------------------------------------------------------------------------- 30Types1. the notion of the set of base types of a type T ,2. the notion of a type T in some class C seen from some prefix type S,3. the notion of the set of member bindings of some type T . These notions are defined mutually recursively as follows.1. The set of base types of a type is a set of class types, given as follows.· The base types of a class type C with parents T1, ..., Tn are C itself, as well as the base types of the compound type T1 with ... with Tn {R }.· The base types of an aliased type are the base types of its alias.· The base types of an abstract type are the base types of its upper bound. · The base types of a parameterized type C [T1, ..., Tn] are the base types oftype C , where every occurrence of a type parameter ai of C has been replacedby the corresponding parameter type Ti . · The base types of a singleton type p.type are the base types of the type of p.· The base types of a compound type T1 with ... with Tn {R } are the re-duced union of the base classes of all Ti 's. This means: Let the multi-set S be the multi-set-union of the base types of all Ti 's. If S contains several typeinstances of the same class, say Si #C [T i , . . . , T i1n ] (i I ) , then all those in- stances are replaced by one of them which conforms to all others. It is anerror if no such instance exists. It follows that the reduced union, if it exists,produces a set of class types, where different types are instances of different classes.· The base types of a type selection S#T are determined as follows. If T is analias or abstract type, the previous clauses apply. Otherwise, T must be a (pos-sibly parameterized) class type, which is defined in some class B . Then the base types of S#T are the base types of T in B seen from the prefix type S.· The base types of an existential type T forSome {Q } are all typesS forSome {Q } where S is a base type of T . 2. The notion of a type T in class C seen from some prefix type S makes sense only ifthe prefix type S has a type instance of class C as a base type, say S #C [T1, ..., Tn].Then we define as follows. · If S =.type, then T in C seen from S is T itself.· Otherwise, if S is an existential type S forSome {Q }, and T in C seen fromS is T , then T in C seen from S is T forSome {Q }. · Otherwise, if T is the i 'th type parameter of some class D, then­ If S has a base typeD[U1, ..., Un], for some type parameters[U1, . . . , Un], then T in C seen from S is Ui . -------------------------------------------------------------------------------3.5 Relations between types31­ Otherwise, if C is defined in a class C , then T in C seen from S is the same as T in C seen from S .­ Otherwise, if C is not defined in another class, then T in C seen from S isT itself.· Otherwise, if T is the singleton type D.this.type for some class D then ­ If D is a subclass of C and S has a type instance of class D among its basetypes, then T in C seen from S is S.­ Otherwise, if C is defined in a class C , then T in C seen from S is the same as T in C seen from S .­ Otherwise, if C is not defined in another class, then T in C seen from S isT itself.· If T is some other type, then the described mapping is performed to all its type components.If T is a possibly parameterized class type, where T 's class is defined in some otherclass D, and S is some prefix type, then we use "T seen from S" as a shorthand for "T in D seen from S".3. The member bindings of a type T are (1) all bindings d such that there exists a typeinstance of some class C among the base types of T and there exists a definition or declaration d in C such that d results from d by replacing every type T in d by Tin C seen from T , and (2) all bindings of the type's refinement (§3.2.7) ,if it has one.The definition of a type projection S#t is the member binding dt of the type t in S. In that case, we also say that S#t is defined by dt . share a to3.5Relations between typesWe define two relations between types.Type equivalenceT UT and U are interchangeable in all contexts. ConformanceT <: UType T conforms to type U .3.5.1 Type EquivalenceEquivalence () between types is the smallest congruence3such that the followingholds: · If t is defined by a type alias type t = T , then t is equivalent to T .· If a path p has a singleton type q.type, then p.type  q.type.3 A congruence is an equivalence relation which is closed under formation of contexts -------------------------------------------------------------------------------32Types· If O is defined by an object definition, and p is a path consisting only of pack-age or object selectors and ending in O, then O.this.type  p.type. · Two compound types (§3.2.7) are equivalent if the sequences of their compo-nent are pairwise equivalent, and occur in the same order, and their refine-ments are equivalent. Two refinements are equivalent if they bind the same names and the modifiers, types and bounds of every declared entity are equiv-alent in both refinements.· Two method types (§3.3.1) are equivalent if they have equivalent result types, both have the same number of parameters, and corresponding parametershave equivalent types. Note that the names of parameters do not matter formethod type equivalence.· Two polymorphic method types (§3.3.2) are equivalent if they have the same number of type parameters, and, after renaming one set of type parameters byanother, the result types as well as lower and upper bounds of correspondingtype parameters are equivalent. · Two existential types (§3.2.10) are equivalent if they have the same numberof quantifiers, and, after renaming one list of type quantifiers by another, thequantified types as well as lower and upper bounds of corresponding quanti- fiers are equivalent.· Two type constructors (§3.3.3) are equivalent if they have the same number oftype parameters, and, after renaming one list of type parameters by another,the result types as well as variances, lower and upper bounds of correspond- ing type parameters are equivalent.3.5.2 ConformanceThe conformance relation (<:) is the smallest transitive relation that satisfies thefollowing conditions.· Conformance includes equivalence. If T U then T <: U . · For every value type T , scala.Nothing <: T <: scala.Any.· For every type constructor T (with any number of type parameters) ,scala.Nothing <: T <: scala.Any.· For every class type T such that T <: scala.AnyRef and not T <: scala.NotNull one has scala.Null <: T .· A type variable or abstract type t conforms to its upper bound and its lowerbound conforms to t .· A class type or parameterized type conforms to any of its base-types. · A singleton type p.type conforms to the type of the path p.· A singleton type p.type conforms to the type scala.Singleton.------------------------------------------------------------------------------- 3.5 Relations between types33· A type projection T #t conforms to U #t if T conforms to U .· A parameterized type T [T1, ..., Tn] conforms to T [U1, ..., Un] if the fol-lowing three conditions hold for i = 1, ..., n. ­ If the i 'th type parameter of T is declared covariant, then Ti <: Ui .­ If the i 'th type parameter of T is declared contravariant, then Ui <: Ti .­ If the i 'th type parameter of T is declared neither covariant nor con- travariant, then Ui  Ti .· A compound type T1 with ... with Tn {R } conforms to each of its compo-nent types Ti .· If T <: Ui for i = 1, ..., n and for every binding d of a type or value x in R there exists a member binding of x in T which subsumes d , then T conforms to thecompound type U1 with ... with Un {R }.· The existential type T forSome {Q } conforms to U if its skolemization (§3.2.10) conforms to U .· The type T conforms to the existential type U forSome {Q } if T conforms toone of the type instances (§3.2.10) of U forSome {Q }.· If Ti  T for ii = 1, . . . , n and U conforms to U then the method type (p1 :T1, ..., pn : Tn) U conforms to (p : T , ..., p11n : Tn ) U .· The polymorphic type [a1 >: L1 <: U1, ..., an >: Ln <: Un]T conforms to the polymorphic type [a1 >: L, . . . , a1 <: U1n >: Ln <: Un ]T if, assuming L1 <:a1 <: U , ..., Land U1n <: an <: Un one has T <: T and Li <: Lii <: Ui fori = 1, ..., n.· Type constructors T and T follow a similar discipline. We characterize Tand T by their type parameter clauses [a1, ..., an] and [a , ..., a 1n ], wherean ai or a may include a variance annotation, a higher-order type param-ieter clause, and bounds. Then, T conforms to T if any list [t1, ..., tn] ­with declared variances, bounds and higher-order type parameter clauses ­ of valid type arguments for T is also a valid list of type arguments for T andT [t1, ..., tn] <: T [t1, ..., tn]. Note that this entails that:­ The bounds on ai must be weaker than the corresponding bounds de- clared for a .i­ The variance of ai must match the variance of a , where covarianceimatches covariance, contravariance matches contravariance and anyvariance matches invariance. ­ Recursively, these restrictions apply to the corresponding higher-ordertype parameter clauses of ai and a .iA declaration or definition in some compound type of class type C subsumes an- other declaration of the same name in some compound type or class type C , if oneof the following holds.------------------------------------------------------------------------------- 34Types· A value declaration or definition that defines a name x with type T subsumesa value or method declaration that defines x with type T , provided T <: T .· A method declaration or definition that defines a name x with type T sub- sumes a method declaration that defines x with type T , provided T <: T .· A type alias type t [T1, ..., Tn] = T subsumes a type alias type t[T1, ..., Tn] = Tif T T .· A type declaration type t [T1, ..., Tn] >: L <: U subsumes a type declara- tion type t [T1, ..., Tn] >: L <: U if L <: L and U <: U .· A type or class definition that binds a type name t subsumes an abstract typedeclaration type t[T1, ..., Tn] >: L <: U if L <: t <: U . The (<:) relation forms pre-order between types, i.e. it is transitive and reflexive.least upper bounds and greatest lower bounds of a set of types are understood to berelative to that order. Note.The least upper bound or greatest lower bound of a set of types does notalways exist. For instance, consider the class definitionsclass A[+T] {}class B extends A[B] class C extends A[C]Then the types A[Any], A[A[Any]], A[A[A[Any]]], ... form a descending se-quence of upper bounds for B and C. The least upper bound would be the infinitelimit of that sequence, which does not exist as a Scala type. Since cases like this are in general impossible to detect, a Scala compiler is free to reject a term which hasa type specified as a least upper or greatest lower bound, and that bound would bemore complex than some compiler-set limit4. The least upper bound or greatest lower bound might also not be unique. For in-stance A with B and B with A are both greatest lower of A and B. If there are severalleast upper bounds or greatest lower bounds, the Scala compiler is free to pick any one of them.3.5.3 Weak ConformanceIn some situations Scala uses a more genral conformance relation. A type S weaklyconforms to a type T , written S <:w T , if S <: T or both S and T are primitive number types and S precedes T in the following ordering.Byte <:w ShortShort <:w Int4The current Scala compiler limits the nesting level of parameterization in such bounds to be at most two deeper than the maximum nesting level of the operand types-------------------------------------------------------------------------------3.6 Volatile Types35Char <:w Int Int <:w LongLong <:w FloatFloat <:w DoubleA weak least upper bound is a least upper bound with respect to weak conformance.3.6Volatile TypesType volatility approximates the possibility that a type parameter or abstract type instance of a type does not have any non-null values. As explained in (§3.1) ,a valuemember of a volatile type cannot appear in a path.A type is volatile if it falls into one of four categories: A compound type T1 with ... with Tn {R } is volatile if one of the following twoconditions hold.1. One of T2, ..., Tn is a type parameter or abstract type, or2. T1 is an abstract type and and either the refinement R or a type Tj for j > 1 contributes an abstract member to the compound type, or3. one of T1, ..., Tn is a singleton type.Here, a type S contributes an abstract member to a type T if S contains an abstractmember that is also a member of T . A refinement R contributes an abstract member to a type T if R contains an abstract declaration which is also a member of T .A type designator is volatile if it is an alias of a volatile type, or if it designates a typeparameter or abstract type that has a volatile type as its upper bound. A singleton type p.type is volatile, if the underlying type of path p is volatile.An existential type T forSome {Q } is volatile if T is volatile.3.7Type ErasureA type is called generic if it contains type arguments or type variables. Type erasure is a mapping from (possibly generic) types to non-generic types. We write |T | forthe erasure of type T . The erasure mapping is defined as follows.· The erasure of an alias type is the erasure of its right-hand side. · The erasure of an abstract type is the erasure of its upper bound.· The erasure of the parameterized type scala.Array[T1] is scala.Array[|T1|].· The erasure of every other parameterized type T [T1, ..., Tn] is |T |. -------------------------------------------------------------------------------36Types· The erasure of a singleton type p.type is the erasure of the type of p.· The erasure of a type projection T #x is |T |#x. · The erasure of a compound type T1 with ... with Tn {R } is the erasure ofthe intersection dominator of T1, ..., Tn.· The erasure of an existential type T forSome {Q } is |T |.The intersection dominator of a list of types T1, ..., Tn is computed as follows. Let Ti , ..., Tbe the subsequence of types T1imi which are not supertypes of some othertype T j . If this subsequence contains a type designator Tc that refers to a class which is not a trait, the intersection dominator is Tc. Otherwise, the intersection domina-tor is the first element of the subsequence, Ti .1------------------------------------------------------------------------------- Chapter 4Basic Declarations and DefinitionsSyntax:Dcl::=`val' ValDcl|`var' VarDcl|`def' FunDcl |`type' {nl} TypeDclPatVarDef::=`val' PatDef|`var' VarDefDef::=PatVarDef|`def' FunDef |`type' {nl} TypeDef|TmplDefA declaration introduces names and assigns them types. It can form part of a classdefinition (§5.1) or of a refinement in a compound type (§3.2.7) . A definition introduces names that denote terms or types. It can form part of anobject or class definition or it can be local to a block. Both declarations and defini-tions produce bindings that associate type names with type definitions or bounds, and that associate term names with types.The scope of a name introduced by a declaration or definition is the whole state-ment sequence containing the binding. However, there is a restriction on forward references in blocks: In a statement sequence s1 ... sn making up a block, if a simplename in si refers to an entity defined by s j where j i , then for all sk between andincluding si and s j , · sk cannot be a variable definition.· If sk is a value definition, it must be lazy.-------------------------------------------------------------------------------38Basic Declarations and Definitions 4.1Value Declarations and DefinitionsSyntax:Dcl::=`val' ValDclValDcl::=ids `:' TypePatVarDef::= `val' PatDefPatDef::=Pattern2 {`,' Pattern2} [`:' Type] `=' Exprids::=id {`,' id}A value declaration val x: T introduces x as a name of a value of type T . A value definition val x: T = e defines x as a name of the value that results fromthe evaluation of e. If the value definition is not recursive, the type T may be omit-ted, in which case the packed type (§6.1) of expression e is assumed. If a type T is given, then e is expected to conform to it.Evaluation of the value definition implies evaluation of its right-hand side e, unlessit has the modifier lazy. The effect of the value definition is to bind x to the value of e converted to type T . A lazy value definition evaluates its right hand side e thefirst time the value is accessed.A constant value definition is of the formfinal val x = e where e is a constant expression (§6.24) .The final modifier must be present andno type annotation may be given. References to the constant value x are themselvestreated as constant expressions; in the generated code they are replaced by the def- inition's right-hand side e.Value definitions can alternatively have a pattern (§8.1) as left-hand side. If p issome pattern other than a simple name or a name followed by a colon and a type, then the value definition val p = e is expanded as follows:1. If the pattern p has bound variables x1, ..., xn, where n > 1:val $x = e match {case p => (x1, . . . , xn) }val x1 = $x.1 . . .val xn = $x.n .Here, $x is a fresh name.2. If p has a unique bound variable x:val x = e match { case p => x }3. If p has no bound variables:e match { case p => () } -------------------------------------------------------------------------------4.2 Variable Declarations and Definitions39Example 4.1.1 The following are examples of value definitions     val pi = 3.1415    val pi: Double = 3.1415    // equivalent to first definition    val Some(x) = f()    // a pattern definition    val x :: xs = mylist     // an infix pattern definition    The last two definitions have the following expansions.    val x = f() match { case Some(x) => x }    val x$ = mylist match { case x :: xs => (x, xs) }     val x = x$.1    val xs = x$.2
The name of any declared or defined value may not end in =.A value declaration val x1, ..., xn: T is a shorthand for the sequence of value dec- larations val x1: T ; ...; val xn: T . A value definition val p1, ..., pn = e isa shorthand for the sequence of value definitions val p1 = e; ...; val pn = e.A value definition val p1, ..., pn : T = e is a shorthand for the sequence of value definitions val p1 : T = e; ...; val pn : T = e.4.2Variable Declarations and DefinitionsSyntax:Dcl::=`var' VarDclPatVarDef::= `var' VarDefVarDcl::=ids `:' TypeVarDef::=PatDef|ids `:' Type `=' `'A variable declaration var x: T is equivalent to declarations of a getter function x and a setter function x=, defined as follows:def x: Tdef x= (y: T ) : UnitAn implementation of a class containing variable declarations may define thesevariables using variable definitions, or it may define setter and getter functions di- rectly.A variable definition var x: T = e introduces a mutable variable with type T andinitial value as given by the expression e. The type T can be omitted, in which casethe type of e is assumed. If T is given, then e is expected to conform to it (§6.1) . Variable definitions can alternatively have a pattern (§8.1) as left-hand side. A vari--------------------------------------------------------------------------------40Basic Declarations and Definitions able definition var p = e where p is a pattern other than a simple name or a namefollowed by a colon and a type is expanded in the same way (§4.1) as a value defi-nition val p = e, except that the free names in p are introduced as mutable vari- ables, not values.The name of any declared or defined variable may not end in =.A variable definition var x: T = _ can appear only as a member of a template. Itintroduces a mutable field with type T and a default initial value. The default value depends on the type T as follows:0if T is Int or one of its subrange types,0Lif T is Long,0.0fif T is Float,0.0dif T is Double, falseif T is Boolean,()if T is Unit,nullfor all other types T .When they occur as members of a template, both forms of variable definition also introduce a getter function x which returns the value currently assigned to the vari-able, as well as a setter function x= which changes the value currently assigned tothe variable. The functions have the same signatures as for a variable declaration. The template then has these getter and setter functions as members, whereas theoriginal variable cannot be accessed directly as a template member.Example 4.2.1 The following example shows how properties can be simulated in Scala. It defines a class TimeOfDayVar of time values with updatable integer fieldsrepresenting hours, minutes, and seconds. Its implementation contains tests thatallow only legal values to be assigned to these fields. The user code, on the other hand, accesses these fields just like normal variables.
    class TimeOfDayVar {      private var h: Int = 0      private var m: Int = 0      private var s: Int = 0       def hours = h      def hours= (h: Int) =        if (0 <= h && h < 24) this.h = h        else throw new DateError()
      def minutes = m       def minutes= (m: Int) =        if (0 <= m && m < 60) this.m = m        else throw new DateError()
      def seconds = s      def seconds= (s: Int) =         if (0 <= s && s < 60) this.s = s        else throw new DateError()    }    val d = new TimeOfDayVar    d.hours = 8; d.minutes = 30; d.seconds = 0     d.hours = 25 // throws a DateError exception
A variable declarationvar x1, . . . , xn: Tis a shorthand for the se-quence of variable declarations var x1: T ; ...; var xn: T .A vari-able definitionvar x1, . . . , xn = eis a shorthand for the sequence ofvariable definitionsvar x1 = e; ...; var xn = e. A variable definitionvar x1, . . . , xn : T = eis a shorthand for the sequence of variable definitionsvar x1 : T = e; ...; var xn : T = e.4.3Type Declarations and Type Aliases Syntax:Dcl::=`type' {nl} TypeDclTypeDcl::=id [TypeParamClause] [`>:' Type] [`<:' Type]Def::=type {nl} TypeDef TypeDef::=id [TypeParamClause] `=' TypeA type declaration type t [tps ] >: L <: U declares t to be an abstract type withlower bound type L and upper bound type U . If the type parameter clause [tps ] is omitted, t abstracts over a first-order type, otherwise t stands for a type constructorthat accepts type arguments as described by the type parameter clause.If a type declaration appears as a member declaration of a type, implementations of the type may implement t with any type T for which L <: T <: U . It is a compile-time error if L does not conform to U . Either or both bounds may be omitted. If thelower bound L is absent, the bottom type scala.Nothing is assumed. If the upper bound U is absent, the top type scala.Any is assumed.A type constructor declaration imposes additional restrictions on the concrete typesfor which t may stand. Besides the bounds L and U , the type parameter clause may impose higher-order bounds and variances, as governed by the conformanceof type constructors (§3.5.2) .The scope of a type parameter extends over the bounds >: L <: U and the type parameter clause tps itself. A higher-order type parameter clause (of an abstracttype constructor t c) has the same kind of scope, restricted to the declaration of thetype parameter t c. Toillustratenestedscoping,thesedeclarationsareallequivalent:type t[m[x] <: Bound[x], Bound[x]],type t[m[x] <: Bound[x], Bound[y]] and type t[m[x] <: Bound[x], Bound[]], as the scope of, e.g., the type param--------------------------------------------------------------------------------42Basic Declarations and Definitions eter of m is limited to the declaration of m. In all of them, t is an abstract typemember that abstracts over two type constructors: m stands for a type constructorthat takes one type parameter and that must be a subtype of B ound , t 's second type constructor parameter. t[MutableList, Iterable] is a valid use of t .A type alias type t = T defines t to be an alias name for the type T . The left handside of a type alias may have a type parameter clause, e.g. type t [tps ] = T . The scope of a type parameter extends over the right hand side T and the type parameterclause tps itself.The scope rules for definitions (§4) and type parameters (§4.6) make it possible that a type name appears in its own bound or in its right-hand side. However, it is a staticerror if a type alias refers recursively to the defined type constructor itself. That is,the type T in a type alias type t [tps ] = T may not refer directly or indirectly to the name t . It is also an error if an abstract type is directly or indirectly its own upperor lower bound.Example 4.3.1 The following are legal type declarations and definitions:type IntList = List[Integer] type T <: Comparable[T]type Two[A] = Tuple2[A, A]type MyCollection[+X] <: Iterable[X]The following are illegal:type Abs = Comparable[Abs]// recursive type alias type S <: T// S, T are bounded by themselves.type T <: Stype T >: Comparable[T.That]// Cannot select from T.// T is a type, not a valuetype MyCollection <: Iterable // Type constructor members must explicitly state their type parameters.If a type alias type t [tps ] = S refers to a class type S, the name t can also be usedas a constructor for objects of type S. Example 4.3.2 The Predef object contains a definition which establishes Pair asan alias of the parameterized class Tuple2:type Pair[+A, +B] = Tuple2[A, B]object Pair {def apply[A, B](x: A, y: B) = Tuple2(x, y) def unapply[A, B](x: Tuple2[A, B]) : Option[Tuple2[A, B]] = Some(x)}-------------------------------------------------------------------------------4.4 Type Parameters43 As a consequence, for any two types S and T , the type Pair[S, T ] is equivalent tothe type Tuple2[S, T ]. Pair can also be used as a constructor instead of Tuple2,as in:val x: Pair[Int, String] = new Pair(1, "abc") 4.4Type ParametersSyntax:TypeParamClause::= `[' VariantTypeParam {`,' VariantTypeParam} `]'VariantTypeParam ::= {Annotation} [`+' | `-'] TypeParam TypeParam::= (id | `') [TypeParamClause] [`>:' Type] [`<:' Type] [`:' Type]Type parameters appear in type definitions, class definitions, and function defini-tions. In this section we consider only type parameter definitions with lower bounds >: L and upper bounds <: U whereas a discussion of context bounds : U andview bounds <% U is deferred to Section 7.4.Themostgeneralformof afirst-ordertypeparameteris@a1 ...@an ± t >: L <: U . Here, L, and U are lower and upper bounds thatconstrain possible type arguments for the parameter. It is a compile-time error if L does not conform to U . ± is a variance, i.e. an optional prefix of either +, or -. Oneor more annotations may precede the type parameter.The names of all type parameters must be pairwise different in their enclosing type parameter clause. The scope of a type parameter includes in each case the wholetype parameter clause. Therefore it is possible that a type parameter appears aspart of its own bounds or the bounds of other type parameters in the same clause. However, a type parameter may not be bounded directly or indirectly by itself.A type constructor parameter adds a nested type parameter clause to thetype parameter.The most general form of a type constructor parameter is @a1 ...@an ± t[tps] >: L <: U .The above scoping restrictions are generalized to the case of nested type parameterclauses, which declare higher-order type parameters. Higher-order type parame- ters (the type parameters of a type parameter t ) are only visible in their immediatelysurrounding parameter clause (possibly including clauses at a deeper nesting level)and in the bounds of t . Therefore, their names must only be pairwise different from the names of other visible parameters. Since the names of higher-order type pa-rameters are thus often irrelevant, they may be denoted with a `', which is nowherevisible.Example 4.4.1 Here are some well-formed type parameter clauses: [S, T]-------------------------------------------------------------------------------44Basic Declarations and Definitions[@specialized T, U][Ex <: Throwable] [A <: Comparable[B], B <: A][A, B >: A, C >: A <: B][M[X], N[X]][M[], N[]] // equivalent to previous clause[M[X <: Bound[X]], Bound[]][M[+X] <: Iterable[X]] The following type parameter clauses are illegal:[A >: A]// illegal, `A' has itself as bound[A <: B, B <: C, C <: A]// illegal, `A' has itself as bound [A, B, C >: A <: B]// illegal lower bound `A' of `C' does// not conform to upper bound `B'.4.5Variance AnnotationsVariance annotations indicate how instances of parameterized types vary with re- spect to subtyping (§3.5.2) .A `+' variance indicates a covariant dependency, a `-'variance indicates a contravariant dependency, and a missing variance indicationindicates an invariant dependency. A variance annotation constrains the way the annotated type variable may ap-pear in the type or class which binds the type parameter. In a type definitiontype T [tps ] = S, or a type declaration type T [tps ] >: L <: U type parameters labeled `+' must only appear in covariant position whereas type parameters labeled`-' must only appear in contravariant position. Analogously, for a class definitionclass C [tps ](ps ) extends T { x: S => ...}, type parameters labeled `+' must only appear in covariant position in the self type S and the template T , whereas typeparameters labeled `-' must only appear in contravariant position.The variance position of a type parameter in a type or template is defined as follows. Let the opposite of covariance be contravariance, and the opposite of invariance beitself. The top-level of the type or template is always in covariant position. Thevariance position changes at the following constructs. · The variance position of a method parameter is the opposite of the varianceposition of the enclosing parameter clause.· The variance position of a type parameter is the opposite of the variance po- sition of the enclosing type parameter clause.· The variance position of the lower bound of a type declaration or type param-eter is the opposite of the variance position of the type declaration or param- eter.-------------------------------------------------------------------------------4.5 Variance Annotations45· The type of a mutable variable is always in invariant position. · The prefix S of a type selection S#T is always in invariant position.· For a type argument T of a type S[. . . T . . . ]: If the corresponding type pa-rameter is invariant, then T is in invariant position. If the corresponding type parameter is contravariant, the variance position of T is the opposite of thevariance position of the enclosing type S[. . . T . . . ].References to the type parameters in object-private or object-protected values, vari- ables, or methods (§5.2) of the class are not checked for their variance position. Inthese members the type parameter may appear anywhere without restricting its le-gal variance annotations. Example 4.5.1 The following variance annotation is legal.abstract class P[+A, +B] {def fst: A; def snd: B}With this variance annotation, type instances of P subtype covariantly with respect to their arguments. For instance,P[IOException, String] <: P[Throwable, AnyRef] .If the members of P are mutable variables, the same variance annotation becomesillegal.abstract class Q[+A, +B](x: A, y: B) { var fst: A = x// **** error: illegal variance:var snd: B = y// `A', `B' occur in invariant position.}If the mutable variables are object-private, the class definition becomes legal again: abstract class R[+A, +B](x: A, y: B) {private[this] var fst: A = x// OKprivate[this] var snd: B = y// OK}Example 4.5.2 The following variance annotation is illegal, since a appears in con- travariant position in the parameter of append:abstract class Sequence[+A] {def append(x: Sequence[A]) : Sequence[A]// **** error: illegal variance:// `A' occurs in contravariant position. }-------------------------------------------------------------------------------46Basic Declarations and DefinitionsThe problem can be avoided by generalizing the type of append by means of a lower bound:abstract class Sequence[+A] {def append[B >: A](x: Sequence[B]) : Sequence[B]}Example 4.5.3 Here is a case where a contravariant type parameter is useful. abstract class OutputChannel[-A] {def write(x: A) : Unit}With that annotation, we have that OutputChannel[AnyRef] conforms toOutputChannel[String]. That is, a channel on which one can write any object can substitute for a channel on which one can write only strings.4.6Function Declarations and DefinitionsSyntax:Dcl::=`def' FunDclFunDcl ::=FunSig `:' TypeDef::=`def' FunDefFunDef::=FunSig [`:' Type] `=' ExprFunSig::=id [FunTypeParamClause] ParamClauses FunTypeParamClause ::=`[' TypeParam {`,' TypeParam} `]'ParamClauses::={ParamClause} [[nl] `(' `implicit' Params `) ']ParamClause ::=[nl] `(' [Params] `) '}Params::=Param {`,' Param}Param::={Annotation} id [`:' ParamType] [`=' Expr]ParamType ::=Type|`=>' Type|Type `*'A function declaration has the form def f psig: T , where f is the function'sname, psig is its parameter signature and T is its result type. A function definition def f psig: T = e also includes a function body e, i.e. an expression which definesthe function's result. A parameter signature consists of an optional type parameterclause [tps ], followed by zero or more value parameter clauses (ps1) ...(psn) . Such a declaration or definition introduces a value with a (possibly polymorphic) methodtype whose parameter types and result type are as given.The type of the function body is expected to conform (§6.1) to the function's de- clared result type, if one is given. If the function definition is not recursive, the re--------------------------------------------------------------------------------4.6 Function Declarations and Definitions 47sult type may be omitted, in which case it is determined from the packed type of thefunction body.A type parameter clause tps consists of one or more type declarations (§4.3) ,which introduce type parameters, possibly with bounds. The scope of a type parameterincludes the whole signature, including any of the type parameter bounds as well asthe function body, if it is present. A value parameter clause ps consists of zero or more formal parameter bindingssuch as x: T or x : T = e, which bind value parameters and associate them withtheir types. Each value parameter declaration may optionally define a default argu- ment. The default argument expression e is type-checked with an expected type Tobtained by replacing all occurences of the function's type parameters in T by theundefined type.For every parameter pi,j with a default argument a method named f $default$n is generated which computes the default argument expression. Here, n denotes theparameter's position in the method declaration. These methods are parametrizedby the type parameter clause [tps ] and all value parameter clauses (ps1) ...(psi-1) preceeding pi,j . The f $default$n methods are inaccessible for user programs.The scope of a formal value parameter name x comprises all subsequent parameterclauses, as well as the method return type and the function body, if they are given.1 Both type parameter names and value parameter names must be pairwise distinct.Example 4.6.1 In the methoddef compare[T](a: T = 0) (b: T = a) = (a == b)the default expression 0 is type-checked with an undefined expected type. When applying compare() , the default value 0 is inserted and T is instantiated to Int. Themethods computing the default arguments have the form:def compare$default$1[T]: Int = 0def compare$default$2[T](a: T) : T = a 4.6.1 By-Name ParametersSyntax:ParamType::=`=>' TypeThe type of a value parameter may be prefixed by =>, e.g. x: => T . The type ofsuch a parameter is then the parameterless method type => T . This indicates that the corresponding argument is not evaluated at the point of function application,1However, at present singleton types of method parameters may only appear in the methodbody; so dependent method types are not supported. -------------------------------------------------------------------------------48Basic Declarations and Definitionsbut instead is evaluated at each use within the function. That is, the argument is evaluated using call-by-name.The by-name modifier is disallowed for parameters of classes that carry a val orvar prefix, including parameters of case classes for which a val prefix is implicitly generated. The by-name modifier is also disallowed for implicit parameters (§7.2) .Example 4.6.2 The declarationdef whileLoop (cond: => Boolean) (stat: => Unit) : Unitindicates that both parameters of whileLoop are evaluated using call-by-name. 4.6.2 Repeated ParametersSyntax:ParamType::=Type `*'The last value parameter of a parameter section may be suffixed by "*", e.g.(..., x:T *) . The type of such a repeated parameter inside the method is then the sequence type scala.Seq[T ]. Methods with repeated parameters T * takea variable number of arguments of type T . That is, if a method m with type(p1 : T1, . . . , pn : Tn, ps : S*) U is applied to arguments (e1, . . . , ek) where k n, then m is taken in that application to have type (p1 : T1, ..., pn : Tn, ps : S, ..., ps S) U ,with k - n occurrences of type S where any parameter names beyond ps arefresh. The only exception to this rule is if the last argument is marked to be a sequence argument via a * type annotation. If m above is applied to argu-ments (e1, ..., en,e : *) , then the type of m in that application is taken to be(p1 : T1, . . . , pn : Tn, ps :scala.Seq[S]) . It is not allowed to define any default arguments in a parameter section with a re-peated parameter.Example 4.6.3 The following method definition computes the sum of the squaresof a variable number of integer arguments. def sum(args: Int*) = {var result = 0for (arg <- args) result += arg * argresult}The following applications of this method yield 0, 1, 6, in that order. sum()sum(1)sum(1, 2, 3)-------------------------------------------------------------------------------4.6 Function Declarations and Definitions49Furthermore, assume the definition: val xs = List(1, 2, 3)The following application of method sum is ill-formed:sum(xs)// ***** error: expected: Int, found: List[Int]By contrast, the following application is well formed and yields again the result 6: sum(xs: *)4.6.3 ProceduresSyntax:FunDcl::=FunSigFunDef::=FunSig [nl] `{' Block `}'Special syntax exists for procedures, i.e. functions that return the Unit value () . A procedure declaration is a function declaration where the result type is omitted.The result type is then implicitly completed to the Unit type. E.g., def f (ps) isequivalent to def f (ps) : Unit. A procedure definition is a function definition where the result type and the equalssign are omitted; its defining expression must be a block. E.g., def f (ps) {stats} isequivalent to def f (ps) : Unit = {stats}. Example 4.6.4 Here is a declaration and a definition of a procedure named write:trait Writer {def write(str: String)}object Terminal extends Writer {def write(str: String) { System.out.println(str) } }The code above is implicitly completed to the following code:trait Writer {def write(str: String) : Unit}object Terminal extends Writer {def write(str: String) : Unit = { System.out.println(str) } }-------------------------------------------------------------------------------50Basic Declarations and Definitions4.6.4 Method Return Type InferenceA class member definition m that overrides some other function m in a base class of C may leave out the return type, even if it is recursive. In this case, the return typeR of the overridden function m , seen as a member of C , is taken as the return typeof m for each recursive invocation of m. That way, a type R for the right-hand side of m can be determined, which is then taken as the return type of m. Note that Rmay be different from R , as long as R conforms to R .Example 4.6.5 Assume the following definitions:trait I { def factorial(x: Int) : Int}class C extends I {def factorial(x: Int) = if (x == 0) 1 else x * factorial(x - 1)}Here, it is OK to leave out the result type of factorial in C, even though the method is recursive.4.7Import ClausesSyntax:Import::= `import' ImportExpr {`,' ImportExpr}ImportExpr::= StableId `.' (id | `' | ImportSelectors) ImportSelectors ::= `{' {ImportSelector `,'}(ImportSelector | `') `}'ImportSelector::= id [`=>' id | `=>' `']An import clause has the form import p.I where p is a stable identifier (§3.1) and I is an import expression. The import expression determines a set of names of im-portable members of p which are made available without qualification. A memberm of p is importable if it is not object-private (§5.2) .The most general form of an import expression is a list of import selectors{ x1 => y1, . . . , xn => yn, _ } .for n 0, where the final wildcard `' may be absent. It makes available each im-portable member p.xi under the unqualified name yi . I.e. every import selector xi => yi renames p.xi to yi . If a final wildcard is present, all importable mem-bers z of p other than x1, ..., xn, y1, ..., yn are also made available under their ownunqualified names. Import selectors work in the same way for type and term members. For instance, an-------------------------------------------------------------------------------4.7 Import Clauses51 import clause import p.{x => y } renames the term name p.x to the term namey and the type name p.x to the type name y. At least one of these two names mustreference an importable member of p. If the target in an import selector is a wildcard, the import selector hides access tothe source member. For instance, the import selector x => _ "renames" x to thewildcard symbol (which is unaccessible as a name in user programs) , and thereby effectively prevents unqualified access to x. This is useful if there is a final wild-card in the same import selector list, which imports all members not mentioned inprevious import selectors. The scope of a binding introduced by an import-clause starts immediately after theimport clause and extends to the end of the enclosing block, template, packageclause, or compilation unit, whichever comes first. Several shorthands exist. An import selector may be just a simple name x. Inthis case, x is imported without renaming, so the import selector is equivalent tox => x. Furthermore, it is possible to replace the whole import selector list by a single identifier or wildcard. The import clause import p.x is equivalent toimport p.{x } , i.e. it makes available without qualification the member x of p. Theimport clause import p._ is equivalent to import p.{}, i.e. it makes available without qualification all members of p (this is analogous to import p.* in Java) .An import clause with multiple import expressions import p1.I1, ..., pn.In is in-terpreted as a sequence of import clauses import p1.I1; ...; import pn.In. Example 4.7.1 Consider the object definition:object M {def z = 0, one = 1def add(x: Int, y: Int) : Int = x + y}Then the block{ import M.{one, z => zero, }; add(zero, one) } is equivalent to the block{ M.add(M.z, M.one) } .-------------------------------------------------------------------------------------------------------------------------------------------------------------- Chapter 5Classes and ObjectsSyntax:TmplDef::= [`case'] `class' ClassDef|[`case'] `object' ObjectDef|`trait' TraitDef Classes (§5.3) and objects (§5.4) are both defined in terms of templates.5.1TemplatesSyntax:ClassTemplate::=[EarlyDefs] ClassParents [TemplateBody] TraitTemplate::=[EarlyDefs] TraitParents [TemplateBody]ClassParents::=Constr {`with' AnnotType}TraitParents::=AnnotType {`with' AnnotType} TemplateBody::=[nl] `{' [SelfType] TemplateStat {semi TemplateStat} `}'SelfType::=id [`:' Type] `=>'|this `:' Type `=>' A template defines the type signature, behavior and initial state of a traitor class of objects or of a single object.Templates form part of instancecreation expressions, class definitions, and object definitions. A templatesc with mt1 with ... with mtn {stats} consists of a constructor invocation scwhich defines the template's superclass, trait references mt1, ..., mtn (n 0) , whichdefine the template's traits, and a statement sequence stats which contains initial- ization code and additional member definitions for the template.Each trait reference mti must denote a trait (§5.3.3) .By contrast, the superclassconstructor sc normally refers to a class which is not a trait. It is possible to write -------------------------------------------------------------------------------54Classes and Objectsa list of parents that starts with a trait reference, e.g. mt1 with ... with mtn. In that case the list of parents is implicitly extended to include the supertype of mt1as first parent type. The new supertype must have at least one constructor thatdoes not take parameters. In the following, we will always assume that this implicit extension has been performed, so that the first parent class of a template is a regularsuperclass constructor, not a trait reference.The list of parents of every class is also always implicitly extended by a reference to the scala.ScalaObject trait as last mixin. E.g.sc with mt1 with ... with mtn {stats}becomesmt1 with ... with mtn with ScalaObject {stats}.The list of parents of a template must be well-formed. This means that the class denoted by the superclass constructor sc must be a subclass of the superclassesof all the traits mt1, ..., mtn. In other words, the non-trait classes inherited by atemplate form a chain in the inheritance hierarchy which starts with the template's superclass.The least proper supertype of a template is the class type or compound type (§3.2.7)consisting of all its parent class types.The statement sequence stats contains member definitions that define new mem- bers or overwrite members in the parent classes. If the template forms part of anabstract class or trait definition, the statement part stats may also contain declara-tions of abstract members. If the template forms part of a concrete class definition, stats may still contain declarations of abstract type members, but not of abstractterm members. Furthermore, stats may in any case also contain expressions; theseare executed in the order they are given as part of the initialization of a template. The sequence of template statements may be prefixed with a formal parameter def-inition and an arrow, e.g. x =>, or x:T =>. If a formal parameter is given, it canbe used as an alias for the reference this throughout the body of the template. If the formal parameter comes with a type T , this definition affects the self type S ofthe underlying class or object as follows: Let C be the type of the class or trait orobject defining the template. If a type T is given for the formal self parameter, S is the greatest lower bound of T and C . If no type T is given, S is just C . Inside thetemplate, the type of this is assumed to be S.The self type of a class or object must conform to the self types of all classes which are inherited by the template t .A second form of self type annotation reads just this: S =>. It prescribes the typeS for this without introducing an alias name for it.Example 5.1.1 Consider the following class definitions: -------------------------------------------------------------------------------5.1 Templates55class Base extends Object {}trait Mixin extends Base {}object O extends Mixin {} In this case, the definition of O is expanded to:object O extends Base with Mixin {}Inheriting from Java Types.A template may have a Java class as its superclass andJava interfaces as its mixins. Template Evaluation.Consider a template sc with mt1 with mtn {stats}.If this is the template of a trait (§5.3.3) then its mixin-evaluation consists of an eval-uation of the statement sequence stats. If this is not a template of a trait, then its evaluation consists of the following steps.· First, the superclass constructor sc is evaluated (§5.1.1) .· Then, all base classes in the template's linearization (§5.1.2) up to the tem- plate's superclass denoted by sc are mixin-evaluated. Mixin-evaluation hap-pens in reverse order of occurrence in the linearization.· Finally the statement sequence stats is evaluated. Delayed Initializaton.The initialization code of an object or class (but not atrait) that follows the superclass constructor invocation and the mixin-evaluationof the template's base classes is passed to a special hook, which is inaccessible from user code. Normally, that hook simply executes the code that is passed toit. But templates inheriting the scala.DelayedInit trait can override the hook byre-implementing the delayedInit method, which is defined as follows: def delayedInit(body: => Unit)5.1.1 Constructor InvocationsSyntax:Constr::=AnnotType {`(' [Exprs] `) '}Constructor invocations define the type, members, and initial state of objects cre- ated by an instance creation expression, or of parts of an object's definition whichare inherited by a class or object definition. A constructor invocation is a functionapplication x.c[targs](args1) ...(argsn) , where x is a stable identifier (§3.1) ,c is a type name which either designates a class or defines an alias type for one, targs is a-------------------------------------------------------------------------------56Classes and Objects type argument list, args1, ..., argsn are argument lists, and there is a constructor ofthat class which is applicable (§6.6) to the given arguments. If the constructor invo-cation uses named or default arguments, it is transformed into a block expression using the same transformation as described in (§6.6.1) .The prefix `x.' can be omitted. A type argument list can be given only if the class ctakes type parameters. Even then it can be omitted, in which case a type argument list is synthesized using local type inference (§6.26.4) .If no explicit arguments aregiven, an empty list () is implicitly supplied.An evaluation of a constructor invocation x.c[targs](args1) ...(argsn) consists of the following steps:· First, the prefix x is evaluated.· Then, the arguments args1, ..., argsn are evaluated from left to right.· Finally, the class being constructed is initialized by evaluating the template of the class referred to by c.5.1.2 Class LinearizationThe classes reachable through transitive closure of the direct inheritance relationfrom a class C are called the base classes of C . Because of mixins, the inheritance re- lationship on base classes forms in general a directed acyclic graph. A linearizationof this graph is defined as follows.Definition 5.1.2 Let C be a class with template C1 with ... with Cn { stats }. The linearization of C , L (C ) is defined as follows:L (C) = C , L (Cn) + ... + L (C1)Here + denotes concatenation where elements of the right operand replace identi-cal elements of the left operand: {a, A} + B = a,(A + B) ifa B= A + Bifa BExample 5.1.3 Consider the following class definitions.abstract class AbsIterator extends AnyRef { ... }trait RichIterator extends AbsIterator { ... } class StringIterator extends AbsIterator { ... }class Iter extends StringIterator with RichIterator { ... }Then the linearization of class Iter is{ Iter, RichIterator, StringIterator, AbsIterator, ScalaObject, AnyRef, Any } -------------------------------------------------------------------------------5.1 Templates57Trait ScalaObject appears in this list because it is added as last mixin to every Scala class (§5.1) .Note that the linearization of a class refines the inheritance relation: if C is a sub-class of D, then C precedes D in any linearization where both C and D occur. Defi- nition 5.1.2also satisfies the property that a linearization of a class always containsthe linearization of its direct superclass as a suffix. For instance, the linearization ofStringIterator is { StringIterator, AbsIterator, ScalaObject, AnyRef, Any }which is a suffix of the linearization of its subclass Iter. The same is not true for thelinearization of mixins. For instance, the linearization of RichIterator is { RichIterator, AbsIterator, ScalaObject, AnyRef, Any }which is not a suffix of the linearization of Iter.5.1.3 Class MembersA class C defined by a template C1 with ... with Cn { stats } can define mem- bers in its statement sequence stats and can inherit members from all parentclasses. Scala adopts Java and C#'s conventions for static overloading of methods. Itis thus possible that a class defines and/or inherits several methods with the same name. To decide whether a defined member of a class C overrides a member of aparent class, or whether the two co-exist as overloaded variants in C , Scala uses thefollowing definition of matching on members: Definition 5.1.4 A member definition M matches a member definition M , if M andM bind the same name, and one of following holds.1. Neither M nor M is a method definition.2. M and M define both monomorphic methods with equivalent argument types.3. M defines a parameterless method and M defines a method with an emptyparameter list () or vice versa.4. M and M define both polymorphic methods with equal number of argument types T , T and equal numbers of type parameters t , t , say, and T = [t /t]T .Member definitions fall into two categories: concrete and abstract. Members ofclass C are either directly defined (i.e. they appear in C 's statement sequence stats) or they are inherited. There are two rules that determine the set of members of aclass, one for each category:------------------------------------------------------------------------------- 58Classes and ObjectsDefinition 5.1.5 A concrete member of a class C is any concrete definition M insome class Ci  L (C ) , except if there is a preceding class C j  L (C ) where j < i which directly defines a concrete member M matching M .An abstract member of a class C is any abstract definition M in some class Ci  L (C ) ,except if C contains already a concrete member M matching M , or if there is a preceding class C j  L (C ) where j < i which directly defines an abstract memberM matching M .This definition also determines the overriding relationships between matchingmembers of a class C and its parents (§5.1.4) .First, a concrete definition always overrides an abstract definition. Second, for definitions M and M ' which are bothconcrete or both abstract, M overrides M if M appears in a class that precedes (inthe linearization of C ) the class in which M is defined. It is an error if a template directly defines two matching members. It is also an errorif a template contains two members (directly defined or inherited) with the samename and the same erased type (§3.7) .Finally, a template is not allowed to contain two methods (directly defined or inherited) with the same name which both definedefault arguments.Example 5.1.6 Consider the trait definitions:trait A { def f: Int }trait B extends A { def f: Int = 1 ; def g: Int = 2 ; def h: Int = 3 } trait C extends A { override def f: Int = 4 ; def g: Int }trait D extends B with C { def h: Int }Then trait D has a directly defined abstract member h. It inherits member f fromtrait C and member g from trait B. 5.1.4 OverridingA member M of class C that matches (§5.1.3) a non-private member M of a baseclass of C is said to override that member. In this case the binding of the overrid-ing member M must subsume (§3.5.2) the binding of the overridden member M . Furthermore, the following restrictions on modifiers apply to M and M :· M must not be labeled final.· M must not be private (§5.2) .· If M is labeled private[C ] for some enclosing class or package C , then M must be labeled private[C ] for some class or package C where C equals Cor C is contained in C .· If M is labeled protected, then M must also be labeled protected.------------------------------------------------------------------------------- 5.1 Templates59· If M is not an abstract member, then M must be labeled override. Further-more, one of two possibilities must hold:­ either M is defined in a subclass of the class where is M is defined, ­ or both M and M override a third member M which is defined in a baseclass of both the classes containing M and M· If M is incomplete (§5.2) in C then M must be labeled abstract override. · If M and M are both concrete value definitions, then either none of them ismarked lazy or both must be marked lazy.A special rule concerns parameterless methods. If a paramterless method defined as def f : T = ... or def f = ... overrides a method of type () T which has anempty parameter list, then f is also assumed to have an empty parameter list.Another restriction applies to abstract type members: An abstract type member with a volatile type (§3.6) as its upper bound may not override an abstract typemember which does not have a volatile upper bound.An overriding method inherits all default arguments from the definition in the su- perclass. By specifying default arguments in the overriding method it is possible toadd new defaults (if the corresponding parameter in the superclass does not have adefault) or to override the defaults of the superclass (otherwise) . Example 5.1.7 Consider the definitions:trait Root { type T <: Root }trait A extends Root { type T <: A }trait B extends Root { type T <: B }trait C extends A with B Then the class definition C is not well-formed because the binding of T in C istype T <: B, which fails to subsume the binding type T <: A of T in type A. Theproblem can be solved by adding an overriding definition of type T in class C: class C extends A with B { type T <: C }5.1.5 Inheritance ClosureLet C be a class type. The inheritance closure of C is the smallest set S of types suchthat· If T is in S , then every type T which forms syntactically a part of T is also in S .· If T is a class type in S , then all parents (§5.1) of T are also in S .It is a static error if the inheritance closure of a class type consists of an infinite num-ber of types. (This restriction is necessary to make subtyping decidable [KP07]) . -------------------------------------------------------------------------------60Classes and Objects5.1.6 Early DefinitionsSyntax:EarlyDefs::= `{' [EarlyDef {semi EarlyDef}] `}' `with' EarlyDef::={Annotation} {Modifier} PatVarDefA template may start with an early field definition clause, which serves to definecertain field values before the supertype constructor is called. In a template { val p1: T1 = e1...val pn: Tn = en} with sc with mt1 with mtn {stats}The initial pattern definitions of p1, ..., pn are called early definitions. They definefields which form part of the template. Every early definition must define at least one variable.An early definition is type-checked and evaluated in the scope which is in effectjust before the template being defined, augmented by any type parameters of theenclosing class and by any early definitions preceding the one being defined. In particular, any reference to this in the right-hand side of an early definition refersto the identity of this just outside the template. Consequently, it is impossible thatan early definition refers to the object being constructed by the template, or refers to one of its fields and methods, except for any other preceding early definition in thesame section. Furthermore, references to preceding early definitions always refer tothe value that's defined there, and do not take into account overriding definitions. In other words, a block of early definitions is evaluated exactly as if it was a localbock containing a number of value definitions.Early definitions are evaluated in the order they are being defined before the super- class constructor of the template is called.Example 5.1.8 Early definitions are particularly useful for traits, which do not havenormal constructor parameters. Example:trait Greeting { val name: Stringval msg = "How are you, "+name}class C extends {val name = "Bob"} with Greeting {println(msg)} In the code above, the field name is initialized before the constructor of Greeting-------------------------------------------------------------------------------5.2 Modifiers61 is called.Therefore, field msg in class Greeting is properly initialized to"How are you, Bob".If name had been initialized instead in C's normal class body, it would be initial- ized after the constructor of Greeting. In that case, msg would be initialized to"How are you, <null>".5.2ModifiersSyntax:Modifier::= LocalModifier|AccessModifier|`override'LocalModifier::=`abstract'|`final'|`sealed' |`implicit'|`lazy'AccessModifier::=(`private' | `protected') [AccessQualifier]AccessQualifier::=`[' (id | `this') `]' Member definitions may be preceded by modifiers which affect the accessibility andusage of the identifiers bound by them. If several modifiers are given, their orderdoes not matter, but the same modifier may not occur more than once. Modifiers preceding a repeated definition apply to all constituent definitions. The rules gov-erning the validity and meaning of a modifier are as follows.· The private modifier can be used with any definition or declaration in a tem- plate. Such members can be accessed only from within the directly enclos-ing template and its companion module or companion class (§5.4) .They arenot inherited by subclasses and they may not override definitions in parent classes.The modifier can be qualified with an identifier C (e.g. private[C ]) that mustdenote a class or package enclosing the definition. Members labeled withsuch a modifier are accessible respectively only from code inside the pack- age C or only from code inside the class C and its companion module (§5.4) .Such members are also inherited only from templates inside C .An different form of qualification is private[this]. A member M marked with this modifier can be accessed only from within the object in which it isdefined. That is, a selection p.M is only legal if the prefix is this or O.this,for some class O enclosing the reference. In addition, the restrictions for un- qualified private apply.-------------------------------------------------------------------------------62Classes and ObjectsMembers marked private without a qualifier are called class-private, whereas members labeled with private[this] are called object-private. A memberis private if it is either class-private or object-private, but not if it is markedprivate[C ] where C is an identifier; in the latter case the member is called qualified private.Class-private or object-private members may not be abstract, and may nothave protected or override modifiers.· The protected modifier applies to class member definitions. Protected mem- bers of a class can be accessed from within­ the template of the defining class,­ all templates that have the defining class as a base class,­ the companion module of any of those classes. A protected modifier can be qualified with an identifier C(e.g.protected[C ]) that must denote a class or package enclosing the defi-nition. Members labeled with such a modifier are also accessible respectively from all code inside the package C or from all code inside the class C and itscompanion module (§5.4) .A protected identifier x may be used as a member name in a selection r .xonly if one of the following applies: ­ The access is within the template defining the member, or, if a qualifi-cation C is given, inside the package C , or the class C , or its companionmodule, or­ r is one of the reserved words this and super, or ­ r 's type conforms to a type-instance of the class which contains the ac-cess.A different form of qualification is protected[this]. A member M markedwith this modifier is called object-protected; it can be accessed only from within the object in which it is defined. That is, a selection p.M is only le-gal if the prefix is this or O.this, for some class O enclosing the reference. Inaddition, the restrictions for unqualified protected apply. · The override modifier applies to class member definitions or declarations. Itis mandatory for member definitions or declarations that override some otherconcrete member definition in a parent class. If an override modifier is given, there must be at least one overridden member definition or declaration (ei-ther concrete or abstract) .· The override modifier has an additional significance when combined withthe abstract modifier. That modifier combination is only allowed for value members of traits.-------------------------------------------------------------------------------5.2 Modifiers63We call a member M of a template incomplete if it is either abstract (i.e. de- fined by a declaration) , or it is labeled abstract and override and every mem-ber overridden by M is again incomplete.Note that the abstract override modifier combination does not influence the concept whether a member is concrete or abstract. A member is abstractif only a declaration is given for it; it is concrete if a full definition is given.· The abstract modifier is used in class definitions. It is redundant for traits, and mandatory for all other classes which have incomplete members. Ab-stract classes cannot be instantiated (§6.10) with a constructor invocation un-less followed by mixins and/or a refinement which override all incomplete members of the class. Only abstract classes and traits can have abstract termmembers.The abstract modifier can also be used in conjunction with override forclass member definitions. In that case the previous discussion applies. · The final modifier applies to class member definitions and to class defini-tions. A final class member definition may not be overridden in subclasses.A final class may not be inherited by a template. final is redundant for ob- ject definitions. Members of final classes or objects are implicitly also final, sothe final modifier is generally redundant for them, too. Note, however, thatconstant value definitions (§4.1) do require an explicit final modifier, even if they are defined in a final class or object. final may not be applied to incom-plete members, and it may not be combined in one modifier list with sealed.· The sealed modifier applies to class definitions. A sealed class may not be di- rectly inherited, except if the inheriting template is defined in the same sourcefile as the inherited class. However, subclasses of a sealed class can be inher-ited anywhere.· The lazy modifier applies to value definitions. A lazy value is initialized the first time it is accessed (which might never happen at all) . Attempting to ac-cess a lazy value during its initialization might lead to looping behavior. Ifan exception is thrown during initialization, the value is considered uninitial- ized, and a later access will retry to evaluate its right hand side.Example 5.2.1 The following code illustrates the use of qualified private:package outerpkg.innerpkgclass Outer { class Inner {private[Outer] def f()private[innerpkg] def g()private[outerpkg] def h()}}------------------------------------------------------------------------------- 64Classes and ObjectsHere, accesses to the method f can appear anywhere within OuterClass, butnot outside it. Accesses to method g can appear anywhere within the packageouterpkg.innerpkg, as would be the case for package-private methods in Java. Fi- nally, accesses to method h can appear anywhere within package outerpkg, includ-ing packages contained in it.Example 5.2.2 A useful idiom to prevent clients of a class from constructing new instances of that class is to declare the class abstract and sealed:object m {abstract sealed class C (x: Int) {def nextC = new C(x + 1) {}}val empty = new C(0) {} }For instance, in the code above clients can create instances of class m.C only by call-ing the nextC method of an existing m.C object; it is not possible for clients to createobjects of class m.C directly. Indeed the following two lines are both in error: new m.C(0)// **** error: C is abstract, so it cannot be instantiated.new m.C(0) {} // **** error: illegal inheritance from sealed class.A similar access restriction can be achieved by marking the primary constructor private (see Example 5.3.2) .5.3Class DefinitionsSyntax:TmplDef::=`class' ClassDefClassDef::=id [TypeParamClause] {Annotation} [AccessModifier] ClassParamClauses ClassTemplateOptClassParamClauses ::={ClassParamClause}[[nl] `(' implicit ClassParams `) ']ClassParamClause::= [nl] `(' [ClassParams] ') 'ClassParams::=ClassParam {`,' ClassParam}ClassParam::={Annotation} [{Modifier} (`val' | `var') ] id [`:' ParamType] [`=' Expr]ClassTemplateOpt::=`extends' ClassTemplate | [[`extends'] TemplateBody]The most general form of class definition isclass c[tps ] as m(ps1) ...(psn) extends t (n 0) .Here,-------------------------------------------------------------------------------5.3 Class Definitions65c is the name of the class to be defined. tps is a non-empty list of type parameters of the class being defined. Thescope of a type parameter is the whole class definition including the type pa-rameter section itself. It is illegal to define two type parameters with the same name. The type parameter section [tps ] may be omitted. A class with a typeparameter section is called polymorphic, otherwise it is called monomorphic.as is a possibly empty sequence of annotations (§11) .If any annotations are given, they apply to the primary constructor of the class.m is an access modifier (§5.2) such as private or protected, possibly witha qualification. If such an access modifier is given it applies to the primary constructor to the class.(ps1) ...(psn) are formal value parameter clauses for the primary constructorof the class. The scope of a formal value parameter includes all subsequentparameter sections and the template t . However, a formal value parameter may not form part of the types of any of the parent classes or members of theclass template t . It is illegal to define two formal value parameters with thesame name. If no formal parameter sections are given, an empty parameter section () is assumed.If a formal parameter declaration x : T is preceded by a val or var keyword, anaccessor (getter) definition (§4.2) for this parameter is implicitly added to theclass. The getter introduces a value member x of class c that is defined as an alias of the parameter. If the introducing keyword is var, a setter accessor x=(§4.2) is also implicitly added to the class. In invocation of that setter x=(e)changes the value of the parameter to the result of evaluating e. The formal parameter declaration may contain modifiers, which then carry over to theaccessor definition(s) . A formal parameter prefixed by val or var may not atthe same time be a call-by-name parameter (§4.6.1) . t is a template (§5.1) of the formsc with mt1 with ... with mtm { stats }(m 0)which defines the base classes, behavior and initial state of objects of theclass. The extends clause extends sc with mt1 with ... with mtm can be omitted, in which case extends scala.AnyRef is assumed. The class body{stats } may also be omitted, in which case the empty body {} is assumed.This class definition defines a type c[tps ] and a constructor which when applied to parameters conforming to types ps initializes instances of type c[tps ] by evaluatingthe template t .Example 5.3.1 The following example illustrates val and var parameters of a classC: -------------------------------------------------------------------------------66Classes and Objectsclass C(x: Int, val y: String, var z: List[String])val c = new C(1, "abc", List() ) c.z = c.y :: c.zExample 5.3.2 The following class can be created only from its companion module.object Sensitive {def makeSensitive(credentials: Certificate) : Sensitive =if (credentials == Admin) new Sensitive() else throw new SecurityViolationException}class Sensitive private () {...}5.3.1 Constructor DefinitionsSyntax:FunDef::= `this' ParamClause ParamClauses (`=' ConstrExpr | [nl] ConstrBlock)ConstrExpr::= SelfInvocation|ConstrBlockConstrBlock::= `{' SelfInvocation {semi BlockStat} `}' SelfInvocation ::= `this' ArgumentExprs {ArgumentExprs}A class may have additional constructors besides the primary constructor. Theseare defined by constructor definitions of the form def this(ps1) ...(psn) = e. Such a definition introduces an additional constructor for the enclosing class, withparameters as given in the formal parameter lists ps1, ..., psn, and whose evaluationis defined by the constructor expression e. The scope of each formal parameter is the subsequent parameter sections and the constructor expression e. A constructorexpression is either a self constructor invocation this(args1) ...(argsn) or a blockwhich begins with a self constructor invocation. The self constructor invocation must construct a generic instance of the class. I.e. if the class in question has nameC and type parameters [tps ], then a self constructor invocation must generate aninstance of C [tps ]; it is not permitted to instantiate formal type parameters. The signature and the self constructor invocation of a constructor definition aretype-checked and evaluated in the scope which is in effect at the point of the en-closing class definition, augmented by any type parameters of the enclosing class and by any early definitions (§5.1.6) of the enclosing template. The rest of the con-structor expression is type-checked and evaluated as a function body in the currentclass.If there are auxiliary constructors of a class C , they form together with C 's primary -------------------------------------------------------------------------------5.3 Class Definitions67constructor (§5.3) an overloaded constructor definition. The usual rules for over- loading resolution (§6.26.3) apply for constructor invocations of C , including forthe self constructor invocations in the constructor expressions themselves. How-ever, unlike other methods, constructors are never inherited. To prevent infinite cycles of constructor invocations, there is the restriction that every self constructorinvocation must refer to a constructor definition which precedes it (i.e. it must referto either a preceding auxiliary constructor or the primary constructor of the class) . Example 5.3.3 Consider the class definitionclass LinkedList[A]() {var head = _var tail = nulldef isEmpty = tail != nulldef this(head: A) = { this() ; this.head = head } def this(head: A, tail: List[A]) = { this(head) ; this.tail = tail }}This defines a class LinkedList with three constructors. The second constructorconstructs an singleton list, while the third one constructs a list with a given head and tail.5.3.2 Case ClassesSyntax:TmplDef::=`case' `class' ClassDefIf a class definition is prefixed with case, the class is said to be a case class. The formal parameters in the first parameter section of a case class are called el-ements; they are treated specially. First, the value of such a parameter can be ex-tracted as a field of a constructor pattern. Second, a val prefix is implicitly added to such a parameter, unless the parameter carries already a val or var modifier. Hence,an accessor definition for the parameter is generated (§5.3) .A case class definition of c[tps ](ps1 ) ...(psn) with type parameters tps and value parameters ps implicitly generates an extractor object (§8.1.8) which is defined asfollows:object c {def apply[tps ](ps1 ) ...(psn) : c[tps] = new c[Ts](xs1 ) ...(xsn)def unapply[tps ](x: c[tps ]) = if (x eq null) scala.Noneelse scala.Some(x.xs11, . . . , x.xs1k)}Here, Ts stands for the vector of types defined in the type parameter section------------------------------------------------------------------------------- 68Classes and Objectstps, each xsi denotes the parameter names of the parameter section psi , andxs11, ..., xs1k denote the names of all parameters in the first parameter section xs1. If a type parameter section is missing in the class, it is also missing in the apply andunapply methods. The definition of apply is omitted if class c is abstract.If the case class definition contains an empty value parameter list, the unapply method returns a Boolean instead of an Option type and is defined as follows:def unapply[tps ](x: c[tps ]) = x ne nullThe name of the unapply method is changed to unapplySeq if the first parameter section ps1 of c ends in a repeated parameter of (§4.6.2) .If a companion objectc exists already, no new object is created, but the apply and unapply methods areadded to the existing object instead. A method named copy is implicitly added to every case class unless the class alreadyhas a member (directly defined or inherited) with that name. The method is definedas follows:def copy[tps ](ps ) . . .(ps 1n ) : c[tps ] = new c[Ts ](xs1 ) . . .(xsn )Again, Ts stands for the vector of types defined in the type parameter section tps andeach xsi denotes the parameter names of the parameter section ps . Every value iparameter psof the copy method has the form xi , ji , j :Ti , j =this.xi , j , where xi , j andTi,j refer to the name and type of the corresponding class parameter psi,j . Every case class implicitly overrides some method definitions of class scala.AnyRef(§12.1) unless a definition of the same method is already given in the case class itselfor a concrete definition of the same method is given in some base class of the case class different from AnyRef. In particular:Method equals: (Any) Boolean is structural equality, where two instancesare equal if they both belong to the case class in question and they have equal (with respect to equals) constructor arguments.Method hashCode: Int computes a hash-code. If the hashCode methods ofthe data structure members map equal (with respect to equals) values to equal hash-codes, then the case class hashCode method does too.Method toString: String returns a string representation which containsthe name of the class and its elements.Example 5.3.4 Here is the definition of abstract syntax for lambda calculus: class Exprcase class Var(x: String)extends Exprcase class Apply (f: Expr, e: Expr)extends Exprcase class Lambda(x: String, e: Expr) extends Expr -------------------------------------------------------------------------------5.3 Class Definitions69This defines a class Expr with case classes Var, Apply and Lambda. A call-by-value evaluator for lambda expressions could then be written as follows.type Env = String => Valuecase class Value(e: Expr, env: Env)def eval(e: Expr, env: Env) : Value = e match { case Var (x) =>env(x)case Apply(f, g) =>val Value(Lambda (x, e1) , env1) = eval(f, env)val v = eval(g, env)eval (e1, (y => if (y == x) v else env1(y) )) case Lambda(, ) =>Value(e, env)}It is possible to define further case classes that extend type Expr in other parts of theprogram, for instancecase class Number(x: Int) extends Expr This form of extensibility can be excluded by declaring the base class Expr sealed;in this case, all classes that directly extend Expr must be in the same source file asExpr.5.3.3 Traits Syntax:TmplDef::=`trait' TraitDefTraitDef::=id [TypeParamClause] TraitTemplateOptTraitTemplateOpt ::=`extends' TraitTemplate | [[`extends'] TemplateBody] A trait is a class that is meant to be added to some other class as a mixin. Unlikenormal classes, traits cannot have constructor parameters. Furthermore, no con-structor arguments are passed to the superclass of the trait. This is not necessary as traits are initialized after the superclass is initialized.Assume a trait D defines some aspect of an instance x of type C (i.e. D is a base classof C ) . Then the actual supertype of D in x is the compound type consisting of all the base classes in L (C ) that succeed D. The actual supertype gives the context forresolving a super reference in a trait (§6.5) .Note that the actual supertype dependson the type to which the trait is added in a mixin composition; it is not statically known at the time the trait is defined.If D is not a trait, then its actual supertype is simply its least proper supertype (whichis statically known) .------------------------------------------------------------------------------- 70Classes and ObjectsExample 5.3.5 The following trait defines the property of being comparable to ob-jects of some type. It contains an abstract method < and default implementations of the other comparison operators <=, >, and >=.trait Comparable[T <: Comparable[T]] { self: T =>def < (that: T) : Booleandef <=(that: T) : Boolean = this < that || this == that def > (that: T) : Boolean = that < thisdef >=(that: T) : Boolean = that <= this}Example 5.3.6 Consider an abstract class Table that implements maps from a typeof keys A to a type of values B. The class has a method set to enter a new key / value pair into the table, and a method get that returns an optional value matchinga given key. Finally, there is a method apply which is like get, except that it returnsa given default value if the table is undefined for the given key. This class is imple- mented as follows.abstract class Table[A, B](defaultValue: B) {def get(key: A) : Option[B]def set(key: A, value: B)def apply(key: A) = get(key) match {case Some(value) => value case None => defaultValue}}Here is a concrete implementation of the Table class.class ListTable[A, B](defaultValue: B) extends Table[A, B](defaultValue) {private var elems: List[(A, B) ] = Nil def get(key: A) = elems.find(.1.==(key) ).map(.2)def set(key: A, value: B) { elems = (key, value) :: elems }}Here is a trait that prevents concurrent access to the get and set operations of its parent class:trait SynchronizedTable[A, B] extends Table[A, B] {abstract override def get(key: A) : Option[B] =synchronized { super.get(key) }abstract override def set(key: A, value: B) = synchronized { super.set(key, value) }}Note that SynchronizedTable does not pass an argument to its superclass, Table,even though Table is defined with a formal parameter. Note also that the super calls -------------------------------------------------------------------------------5.4 Object Definitions71in SynchronizedTable's get and set methods statically refer to abstract methods in class Table. This is legal, as long as the calling method is labeled abstract override(§5.2) .Finally, the following mixin composition creates a synchronized list table withstrings as keys and integers as values and with a default value 0: object MyTable extends ListTable[String, Int](0) with SynchronizedTable[String, Int]The object MyTable inherits its get and set method from SynchronizedTable. Thesuper calls in these methods are re-bound to refer to the corresponding imple- mentations in ListTable, which is the actual supertype of SynchronizedTable inMyTable.5.4Object DefinitionsSyntax:ObjectDef::=id ClassTemplate An object definition defines a single object of a new class. Its most general form isobject m extends t . Here, m is the name of the object to be defined, and t is atemplate (§5.1) of the form sc with mt1 with ... with mtn { stats }which defines the base classes, behavior and initial state of m.The extendsclause extends sc with mt1 with ... with mtn can be omitted, in which case extends scala.AnyRef is assumed. The class body {stats } may also be omitted,in which case the empty body {} is assumed.The object definition defines a single object (or: module) conforming to the tem- plate t . It is roughly equivalent to the following definition of a lazy value:lazy val m = new sc with mt1 with . . . with mtn { this: m.t y pe => stats }Note that the value defined by an object definition is instantiated lazily. Thenew m$cls constructor is evaluated not at the point of the object definition, but isinstead evaluated the first time m is dereferenced during execution of the program(which might be never at all) . An attempt to dereference m again in the course of evaluation of the constructor leads to a infinite loop or run-time error. Otherthreads trying to dereference m while the constructor is being evaluated block untilevaluation is complete. The expansion given above is not accurate for top-level objects. It cannot be be-cause variable and method definition cannot appear on the top-level outside of apackage object (§9.3) .Instead, top-level objects are translated to static fields. -------------------------------------------------------------------------------72Classes and ObjectsExample 5.4.1 Classes in Scala do not have static members; however, an equivalent effect can be achieved by an accompanying object definition E.g.abstract class Point {val x: Doubleval y: Doubledef isOrigin = (x == 0.0 && y == 0.0)} object Point {val origin = new Point() { val x = 0.0; val y = 0.0 }}This defines a class Point and an object Point which contains origin as a member.Note that the double use of the name Point is legal, since the class definition defines the name Point in the type name space, whereas the object definition defines aname in the term namespace.This technique is applied by the Scala compiler when interpreting a Java class with static members. Such a class C is conceptually seen as a pair of a Scala class thatcontains all instance members of C and a Scala object that contains all static mem-bers of C .Generally, a companion module of a class is an object which has the same name as the class and is defined in the same scope and compilation unit. Conversely, theclass is called the companion class of the module.------------------------------------------------------------------------------- Chapter 6ExpressionsSyntax:Expr::=(Bindings | id | `') `=>' Expr|Expr1Expr1::=`if' `(' Expr `) ' {nl} Expr [[semi] else Expr] |`while' `(' Expr `) ' {nl} Expr|`try' `{' Block `}' [`catch'`{' CaseClauses `}'][`finally' Expr]|`do' Expr [semi] `while' `(' Expr ') ' |`for' (`(' Enumerators `) ' | `{' Enumerators `}'){nl} [`yield'] Expr|`throw' Expr|`return' [Expr]| [SimpleExpr `.'] id `=' Expr|SimpleExpr1 ArgumentExprs `=' Expr|PostfixExpr|PostfixExpr Ascription|PostfixExpr `match' `{' CaseClauses `}' PostfixExpr::=InfixExpr [id [nl]]InfixExpr::=PrefixExpr|InfixExpr id [nl] InfixExprPrefixExpr::=[`-' | `+' | `~' | `!'] SimpleExpr SimpleExpr::=`new' (ClassTemplate | TemplateBody)|BlockExpr|SimpleExpr1 [`']SimpleExpr1::=Literal| Path|`'|`(' [Exprs] `) '|SimpleExpr `.' id s|SimpleExpr TypeArgs------------------------------------------------------------------------------- 74Expressions|SimpleExpr1 ArgumentExprs|XmlExprExprs::=Expr {`,' Expr}BlockExpr::=`{' CaseClauses `}' |`{' Block `}'Block::={BlockStat semi} [ResultExpr]ResultExpr::=Expr1|(Bindings | ([`implicit'] id | `') `:' CompoundType) `=>' Block Ascription::=`:' InfixType|`:' Annotation {Annotation}|`:' `' `*'Expressions are composed of operators and operands. Expression forms are dis- cussed subsequently in decreasing order of precedence.6.1Expression TypingThe typing of expressions is often relative to some expected type (which might beundefined) . When we write "expression e is expected to conform to type T ", we mean: (1) the expected type of e is T , and (2) the type of expression e must conformto T .The following skolemization rule is applied universally for every expression: If thetype of an expression would be an existential type T , then the type of the expression is assumed instead to be a skolemization (§3.2.10) of T .Skolemization is reversed by type packing. Assume an expression e of type T andlet t1[tps1] >: L1 <: U1, ..., tn[tpsn] >: Ln <: Un be all the type variables created by skolemization of some part of e which are free in T . Then the packed type of e isT forSome { type t1[tps1] >: L1 <: U1; ...; type tn[tpsn] >: Ln <: Un }.6.2Literals Syntax:SimpleExpr::=LiteralTyping of literals is as described in (§1.3) ;their evaluation is immediate.------------------------------------------------------------------------------- 6.3 The Null Value756.3The Null ValueThe null value is of type scala.Null, and is thus compatible with every referencetype. It denotes a reference value which refers to a special "null" object. This object implements methods in class scala.AnyRef as follows:· eq(x ) and ==(x ) return true iff the argument x is also the "null" object.· ne(x ) and !=(x ) return true iff the argument x is not also the "null" object. · isInstanceOf[T ] always returns false.· asInstanceOf[T ] returns the "null" object itself if Tconforms toscala.AnyRef, and throws a NullPointerException otherwise. Areferencetoanyothermemberofthe"null"objectcausesaNullPointerException to be thrown. 6.4DesignatorsSyntax:SimpleExpr::=Path|SimpleExpr `.' idA designator refers to a named term. It can be a simple name or a selection. A simple name x refers to a value as specified in §2.If x is bound by a definitionor declaration in an enclosing class or object C , it is taken to be equivalent to theselection C .this.x where C is taken to refer to the class containing x even if the type name C is shadowed (§2) at the occurrence of x.If r is a stable identifier (§3.1) of type T , the selection r.x refers statically to a termmember m of r that is identified in T by the name x. For other expressions e, e.x is typed as if it was { val y = e; y.x }, for some freshname y.The expected type of a designator's prefix is always undefined. The type of a desig-nator is the type T of the entity it refers to, with the following exception: The type of a path (§3.1) p which occurs in a context where a stable type (§3.2.1) is required isthe singleton type p.type.The contexts where a stable type is required are those that satisfy one of the follow- ing conditions:1. The path p occurs as the prefix of a selection and it does not designate a con-stant, or2. The expected type pt is a stable type, or------------------------------------------------------------------------------- 76Expressions3. The expected type pt is an abstract type with a stable type as lower bound,and the type T of the entity referred to by p does not conform to pt, or4. The path p designates a module. The selection e.x is evaluated by first evaluating the qualifier expression e, whichyields an object r , say. The selection's result is then the member of r that is eitherdefined by m or defined by a definition overriding m. If that member has a type which conforms to scala.NotNull, the member's value must be initialized to a valuedifferent from null, otherwise a scala.UnitializedError is thrown.6.5This and SuperSyntax: SimpleExpr::=[id `.'] `this'|[id '.'] `super' [ClassQualifier] `.' idThe expression this can appear in the statement part of a template or compound type. It stands for the object being defined by the innermost template or compoundtype enclosing the reference. If this is a compound type, the type of this is thatcompound type. If it is a template of a class or object definition with simple name C , the type of this is the same as the type of C .this.The expression C .this is legal in the statement part of an enclosing class or objectdefinition with simple name C . It stands for the object being defined by the inner- most such definition. If the expression's expected type is a stable type, or C .thisoccurs as the prefix of a selection, its type is C .this.type, otherwise it is the selftype of class C . A reference super.m refers statically to a method or type m in the least propersupertype of the innermost template containing the reference. It evaluates to themember m in the actual supertype of that template which is equal to m or which overrides m. The statically referenced member m must be a type or a method. Ifit is a method, it must be concrete, or the template containing the reference musthave a member m which overrides m and which is labeled abstract override. A reference C .super.m refers statically to a method or type m in the least propersupertype of the innermost enclosing class or object definition named C which en-closes the reference. It evaluates to the member m in the actual supertype of that class or object which is equal to m or which overrides m. The statically referencedmember m must be a type or a method. If the statically referenced member m isa method, it must be concrete, or the innermost enclosing class or object defini- tion named C must have a member m which overrides m and which is labeledabstract override.-------------------------------------------------------------------------------6.6 Function Applications 77The super prefix may be followed by a trait qualifier [T ], as in C .super[T ].x. Thisis called a static super reference. In this case, the reference is to the type or method ofx in the parent trait of C whose simple name is T . That member must be uniquely defined. If it is a method, it must be concrete.Example 6.5.1 Consider the following class definitionsclass Root { def x = "Root" }class A extends Root { override def x = "A" ; def superA = super.x } trait B extends Root { override def x = "B" ; def superB = super.x }class C extends Root with B {override def x = "C" ; def superC = super.x}class D extends A with B { override def x = "D" ; def superD = super.x}The linearization of class C is {C, B, Root} and the linearization of class D is{D, B, A, Root}. Then we have:(new A) .superA == "Root", (new C) .superB = "Root", (new C) .superC = "B",(new D) .superA == "Root", (new D) .superB = "A",(new D) .superD = "B",Note that the superB function returns different results depending on whether B is mixed in with class Root or A.6.6Function ApplicationsSyntax:SimpleExpr::=SimpleExpr1 ArgumentExprsArgumentExprs ::=`(' [Exprs] `) ' |`(' [Exprs `,'] PostfixExpr `:' `' `*' ') '|[nl] BlockExprExprs::=Expr {`,' Expr}An application f (e1, ..., em) applies the function f to the argument expressions e1, ..., em. If f has a method type (p1:T1, ..., pn:Tn) U , the type of each argumentexpression ei is typed with the corresponding parameter type Ti as expected type.Let Si be type type of argument ei (i = 1, ..., m) . If f is a polymorphic method, local type inference (§6.26.4) is used to determine type arguments for f . If f has somevalue type, the application is taken to be equivalent to f .apply(e1, ..., em) , i.e. theapplication of an apply method defined by f . The function f must be applicable to its arguments e1, ..., en of types S1, ..., Sn.-------------------------------------------------------------------------------78Expressions If f has a method type (p1 : T1, ..., pn : Tn) U we say that an argument expression eiis a named argument if it has the form xi = e and xii is one of the parameter namesp1, ..., pn. The function f is applicable if all of the follwing conditions hold: · For every named argument xi = e the type Sii is compatible with the parame-ter type T j whose name p j matches xi .· For every positional argument ei the type Si is compatible with Ti . · If the expected type is defined, the result type U is compatible to it.If f is a polymorphic method it is applicable if local type inference (§6.26.4) candetermine type arguments so that the instantiated method is applicable. If f has some value type it is applicable if it has a method member named apply which isapplicable.Evaluation of f (e1, ..., en) usually entails evaluation of f and e1, ..., en in that or-der. Each argument expression is converted to the type of its corresponding formal parameter. After that, the application is rewritten to the function's right hand side,with actual arguments substituted for formal parameters. The result of evaluatingthe rewritten right-hand side is finally converted to the function's declared result type, if one is given.The case of a formal parameter with a parameterless method type =>T is treatedspecially. In this case, the corresponding actual argument expression e is not eval- uated before the application. Instead, every use of the formal parameter on theright-hand side of the rewrite rule entails a re-evaluation of e. In other words, theevaluation order for =>-parameters is call-by-name whereas the evaluation order for normal parameters is call-by-value. Furthermore, it is required that e's packedtype (§6.1) conforms to the parameter type T . The behavior of by-name param-eters is preserved if the application is transformed into a block due to named or default arguments. In this case, the local value for that parameter has the formval yi = () => e and the argument passed to the function is yi () .The last argument in an application may be marked as a sequence argument, e.g. e: *. Such an argument must correspond to a repeated parameter (§4.6.2) of typeS* and it must be the only argument matching this parameter (i.e. the number offormal parameters and actual arguments must be the same) . Furthermore, the type of e must conform to scala.Seq[T ], for some type T which conforms to S. In thiscase, the argument list is transformed by replacing the sequence e with its elements.When the application uses named arguments, the vararg parameter has to be spec- ified exactly once.A function application usually allocates a new frame on the program's run-timestack. However, if a local function or a final method calls itself as its last action, the call is executed using the stack-frame of the caller.Example 6.6.1 Assume the following function which computes the sum of a vari-able number of arguments:------------------------------------------------------------------------------- 6.6 Function Applications79def sum(xs: Int*) = (0 /: xs) ((x, y) => x + y)Thensum(1, 2, 3, 4)sum(List(1, 2, 3, 4) : *)both yield 10 as result. On the other hand, sum(List(1, 2, 3, 4) )would not typecheck.6.6.1 Named and Default ArgumentsIf an application might uses named arguments p = e or default arguments, the fol-lowing conditions must hold. · The named arguments form a suffix of the argument list e1, ..., em, i.e. no po-sitional argument follows a named one.· The names xi of all named arguments are pairwise distinct and no named argument defines a parameter which is already specified by a positional argu-ment.· Every formal parameter p j : Tj which is not specified by either a positional ora named argument has a default argument. If the application uses named or default arguments the following transformation isapplied to convert it into an application without named or default arguments.If the function f has the form p.m[targs] it is transformed into the block { val q = pq.m[targs]}If the function f is itself an application expression the transformation is appliedrecursively on f . The result of transforming f is a block of the form { val q = pval x1 = expr1. . .val xk = exprkq.m[targs](args1) , ...,(argsl )}where every argument in (args1) , ..., (argsl ) is a reference to one of the values x1, ..., xk. To integrate the current application into the block, first a value definition-------------------------------------------------------------------------------80Expressions using a fresh name yi is created for every argument in e1, ..., em, which is initialisedto ei for positional arguments and to e for named arguments of the form x.ii = ei Then, for every parameter which is not specified by the argument list, a value defi-nition using a fresh name zi is created, which is initialized using the method com-puting the default argument of this parameter (§4.6) . Let args be a permutation of the generated names yi and zi such such that the po-sition of each name matches the position of its corresponding parameter in themethod type (p1 : T1, ..., pn : Tn) U . The final result of the transformation is a block of the form{ val q = pval x1 = expr1. . .val xl = exprkval y1 = e1. . .val ym = emval z1 = q.m$default$i[targs](args1) , ...,(argsl ) . . .val zd = q.m$default$j[targs](args1) , ...,(argsl )q.m[targs](args1) , ...,(argsl ) (args)}6.7Method ValuesSyntax:SimpleExpr ::=SimpleExpr1 `'The expression e _ is well-formed if e is of method type or if e is a call-by-nameparameter. If e is a method with parameters, e _ represents e converted to a func- tion type by eta expansion (§6.26.5) .If e is a parameterless method or call-by-nameparameter of type =>T , e _ represents the function of type () => T , which evalu-ates e when it is applied to the empty parameterlist () . Example 6.7.1 The method values in the left column are each equivalent to theanonymous functions (§6.23) on their right.Math.sin _x => Math.sin(x)Array.range _ (x1, x2) => Array.range(x1, x2)List.map2 _(x1, x2) => (x3) => List.map2(x1, x2) (x3)List.map2(xs, ys) _x => List.map2(xs, ys) (x)Note that a space is necessary between a method name and the trailing underscore -------------------------------------------------------------------------------6.8 Type Applications81because otherwise the underscore would be considered part of the name. 6.8Type ApplicationsSyntax:SimpleExpr::=SimpleExpr TypeArgsA type application e[T1, ..., Tn] instantiates a polymorphic value e of type[a1 >: L1 <: U1, . . . , an >: Ln <: Un]S with argument types T1, . . . , Tn. Every argument type Ti must obey the corresponding bounds Li and Ui . That is, foreach i = 1, ..., n, we must have Li <: Ti <: Ui , where is the substitution[a1 := T1, ..., an := Tn]. The type of the application is S. If the function part e is of some value type, the type application is taken to be equiv-alent to e.apply[T1, ..., Tn], i.e. the application of an apply method defined bye.Type applications can be omitted if local type inference (§6.26.4) can infer best type parameters for a polymorphic functions from the types of the actual function argu-ments and the expected result type.6.9TuplesSyntax:SimpleExpr::= `(' [Exprs] `) 'A tuple expression (e1, ..., en) is an alias for the class instance creationscala.Tuplen(e1, . . . , en) , where n 2. The empty tuple () is the unique value of type scala.Unit.6.10Instance Creation ExpressionsSyntax:SimpleExpr::=`new' (ClassTemplate | TemplateBody)A simple instance creation expression is of the form new c where c is a constructor invocation (§5.1.1) .Let T be the type of c. Then T must denote a (a type instanceof ) a non-abstract subclass of scala.AnyRef. Furthermore, the concrete self type ofthe expression must conform to the self type of the class denoted by T (§5.1) .The concrete self type is normally T , except if the expression new c appears as the righthand side of a value definition------------------------------------------------------------------------------- 82Expressionsval x: S = new c(where the type annotation : S may be missing) . In the latter case, the concreteself type of the expression is the compound type T with x.type. The expression is evaluated by creating a fresh object of type T which is is initializedby evaluating c. The type of the expression is T .A general instance creation expression is of the form new t for some class template t (§5.1) .Such an expression is equivalent to the block{ class a extends t ; new a }where a is a fresh name of an anonymous class which is inaccessible to user pro-grams.There is also a shorthand form for creating values of structural types: If {D} is a class body, then new {D} is equivalent to the general instance creation expressionnew AnyRef{D}.Example 6.10.1 Consider the following structural instance creation expression:new { def getName() = "aaron" } This is a shorthand for the general instance creation expressionnew AnyRef{ def getName() = "aaron" }The latter is in turn a shorthand for the block{ class anon$X extends AnyRef{ def getName() = "aaron" }; new anon$X } where anon$X is some freshly created name.6.11BlocksSyntax:BlockExpr::=`{' Block `}'Block::={BlockStat semi} [ResultExpr] A block expression {s1; ...; sn; e } is constructed from a sequence of block state-ments s1, ..., sn and a final expression e. The statement sequence may not containtwo definitions or declarations that bind the same name in the same namespace. The final expression can be omitted, in which case the unit value () is assumed.The expected type of the final expression e is the expected type of the block. Theexpected type of all preceding statements is undefined. -------------------------------------------------------------------------------6.12 Prefix, Infix, and Postfix Operations83The type of a block s1; ...; sn; e is T forSome {Q }, where T is the type of e and Q contains existential clauses (§3.2.10) for every value or type name which isfree in T and which is defined locally in one of the statements s1, ..., sn. We say theexistential clause binds the occurrence of the value or type name. Specifically, · A locally defined type definition type t = T is bound by the existential clausetype t >: T <: T . It is an error if t carries type parameters.· A locally defined value definition val x : T = e is bound by the existential clause val x : T .· A locally defined class definition class c extends t is bound by the existen-tial clause type c <: T where T is the least class type or refinement type whichis a proper supertype of the type c. It is an error if c carries type parameters. · A locally defined object definition object x extends t is bound by the existen-tial clause val x : T where T is the least class type or refinement type which isa proper supertype of the type x.type. Evaluation of the block entails evaluation of its statement sequence, followed by anevaluation of the final expression e, which defines the result of the block.Example 6.11.1 Assuming a class Ref[T](x: T) , the block { class C extends B {. . .} ; new Ref(new C) }has the type Ref[1] forSome { type 1 <: B }. The block{ class C extends B {. . .} ; new C }simply has type B, because with the rules in (§3.2.10the existentially quantified type 1 forSome { type 1 <: B } can be simplified to B.6.12Prefix, Infix, and Postfix OperationsSyntax:PostfixExpr::=InfixExpr [id [nl]]InfixExpr ::=PrefixExpr|InfixExpr id [nl] InfixExprPrefixExpr::=[`-' | `+' | `!' | `~'] SimpleExprExpressions can be constructed from operands and operators. -------------------------------------------------------------------------------84Expressions6.12.1 Prefix OperationsA prefix operation op e consists of a prefix operator op, which must be one of the identifiers `+', `-', `!' or `~'. The expression op e is equivalent to the postfix methodapplication e.unaryop.Prefix operators are different from normal function applications in that their operand expression need not be atomic. For instance, the input sequence -sin(x)is read as -(sin(x) ), whereas the function application negate sin(x) would beparsed as the application of the infix operator sin to the operands negate and (x) . 6.12.2 Postfix OperationsA postfix operator can be an arbitrary identifier. The postfix operation e op is inter-preted as e.op.6.12.3 Infix OperationsAn infix operator can be an arbitrary identifier. Infix operators have precedence and associativity defined as follows:The precedence of an infix operator is determined by the operator's first character.Characters are listed below in increasing order of precedence, with characters on the same line having the same precedence.(all letters)|^&< >= !:+ -* / %(all other special characters) That is, operators starting with a letter have lowest precedence, followed by opera-tors starting with `|', etc.There's one exception to this rule, which concerns assignment operators(§6.12.4) . The precedence of an assigment operator is the same as the one of simple assign-ment (=) . That is, it is lower than the precedence of any other operator.The associativity of an operator is determined by the operator's last character. Op- erators ending in a colon `:' are right-associative. All other operators are left-associative.Precedence and associativity of operators determine the grouping of parts of an ex-pression as follows. -------------------------------------------------------------------------------6.12 Prefix, Infix, and Postfix Operations85· If there are several infix operations in an expression, then operators with higher precedence bind more closely than operators with lower precedence.· If there are consecutive infix operations e0 op1 e1 op2 ...opn en with operatorsop1, ..., opn of the same precedence, then all these operators must have the same associativity. If all operators are left-associative, the sequence is inter-preted as (. . . (e0 op1 e1) op2 ...) opn en. Otherwise, if all operators are right-associative, the sequence is interpreted as e0 op1 (e1 op2 (...opn en) ...) . · Postfix operators always have lower precedence than infix operators. E.g.e1 op1 e2 op2 is always equivalent to (e1 op1 e2) op2.The right-hand operand of a left-associative operator may consist of several argu- ments enclosed in parentheses, e.g. e op (e1,...,en) . This expression is then inter-preted as e.op(e1,...,en) .A left-associative binary operation e1 op e2 is interpreted as e1.op(e2) . If op is right- associative, the same operation is interpreted as { val x=e1; e2.op(x ) }, wherex is a fresh name.6.12.4 Assignment OperatorsAn assignment operator is an operator symbol (syntax category op in (§1.1) )that ends in an equals character "=", with the exception of operators for which one of thefollowing conditions holds:(1) the operator also starts with an equals character, or(2) the operator is one of (<=) , (>=) , (!=) . Assignment operators are treated specially in that they can be expanded to assign-ments if no other interpretation is valid.Let's consider an assignment operator such as += in an infix operation l += r , where l , r are expressions. This operation can be re-interpreted as an operationwhich corresponds to the assignmentl = l + rexcept that the operation's left-hand-side l is evaluated only once. The re-interpretation occurs if the following two conditions are fulfilled.1. The left-hand-side l does not have a member named +=, and also cannot beconverted by an implicit conversion (§6.26) to a value with a member named +=.2. The assignment l = l + r is type-correct. In particular this implies that lrefers to a variable or object that can be assigned to, and that is convertibleto a value with a member named +. -------------------------------------------------------------------------------86Expressions6.13Typed ExpressionsSyntax:Expr1::= PostfixExpr `:' CompoundTypeThe typed expression e : T has type T . The type of expression e is expected to con-form to T . The result of the expression is the value of e converted to type T . Example 6.13.1 Here are examples of well-typed and illegally typed expressions.1: Int// legal, of type Int1: Long// legal, of type Long// 1: string// ***** illegal 6.14Annotated ExpressionsSyntax:Expr1::=PostfixExpr `:' Annotation {Annotation}An annotated expression e: @a1 ... @an attaches annotations a1, ..., an to the ex- pression e (§11) .6.15AssignmentsSyntax:Expr1::=[SimpleExpr `.'] id `=' Expr|SimpleExpr1 ArgumentExprs `=' Expr The interpretation of an assignment to a simple variable x = e depends on thedefinition of x. If x denotes a mutable variable, then the assignment changes thecurrent value of x to be the result of evaluating the expression e. The type of e is expected to conform to the type of x. If x is a parameterless function defined insome template, and the same template contains a setter function x= as member,then the assignment x = e is interpreted as the invocation x=(e ) of that setter function. Analogously, an assignment f .x = e to a parameterless function x isinterpreted as the invocation f .x=(e ) .An assignment f (args ) = e with a function application to the left of the `=' oper- ator is interpreted as f .update(args, e ) , i.e. the invocation of an update functiondefined by f .-------------------------------------------------------------------------------6.15 Assignments 87Example 6.15.1 Here are some assignment expressions and their equivalent ex-pansions.x.f = ex.f=(e)x.f() = ex.f.update(e)x.f(i) = e x.f.update(i, e)x.f(i, j) = ex.f.update(i, j, e)Example 6.15.2 Here is the usual imperative code for matrix multiplication.def matmul(xss: Array[Array[Double]], yss: Array[Array[Double]]) = { val zss: Array[Array[Double]] = new Array(xss.length, yss(0) .length)var i = 0while (i < xss.length) {var j = 0while (j < yss(0) .length) {var acc = 0.0 var k = 0while (k < yss.length) {acc = acc + xss(i) (k) * yss(k) (j)k += 1}zss(i) (j) = accj += 1}i += 1} zss}Desugaring the array accesses and assignments yields the following expanded ver-sion:def matmul(xss: Array[Array[Double]], yss: Array[Array[Double]]) = {val zss: Array[Array[Double]] = new Array(xss.length, yss.apply(0) .length) var i = 0while (i < xss.length) {var j = 0while (j < yss.apply(0) .length) {var acc = 0.0var k = 0while (k < yss.length) {acc = acc + xss.apply(i) .apply(k) * yss.apply(k) .apply(j) k += 1}zss.apply(i) .update(j, acc)j += 1-------------------------------------------------------------------------------88Expressions} i += 1}zss}6.16Conditional ExpressionsSyntax:Expr1::=`if' `(' Expr `) ' {nl} Expr [[semi] `else' Expr] The conditional expression if (e1) e2 else e3 chooses one of the values of e2and e3, depending on the value of e1. The condition e1 is expected to conform totype Boolean. The then-part e2 and the else-part e3 are both expected to conform to the expected type of the conditional expression. The type of the conditional expres-sion is the weak least upper bound (§3.5.3) of the types of e2 and e3. A semicolonpreceding the else symbol of a conditional expression is ignored. The conditional expression is evaluated by evaluating first e1. If this evaluates totrue, the result of evaluating e2 is returned, otherwise the result of evaluating e3 isreturned.A short form of the conditional expression eliminates the else-part. The conditional expression if (e1) e2 is evaluated as if it was if (e1) e2 else () .6.17While Loop ExpressionsSyntax:Expr1::=`while' `(' Expr ') ' {nl} Expr The while loop expression while (e1) e2 is typed and evaluated as if it was anapplication of whileLoop (e1) (e2) where the hypothetical function whileLoop isdefined as follows.def whileLoop(cond: => Boolean) (body: => Unit) : Unit =if (cond) { body ; whileLoop(cond) (body) } else {}6.18Do Loop ExpressionsSyntax:------------------------------------------------------------------------------- 6.19 For Comprehensions and For Loops89Expr1::=`do' Expr [semi] `while' `(' Expr ') 'The do loop expression do e1 while (e2) is typed and evaluated as if it was the expression (e1 ; while (e2) e1) . A semicolon preceding the while symbol of ado loop expression is ignored.6.19For Comprehensions and For LoopsSyntax:Expr1 ::=`for' (`(' Enumerators `) ' | `{' Enumerators `}'){nl} [`yield'] ExprEnumerators::=Generator {semi Enumerator}Enumerator ::=Generator|Guard|`val' Pattern1 `=' ExprGenerator::=Pattern1 `<-' Expr [Guard]Guard::= `if' PostfixExprA for loop for (enums ) e executes expression e for each binding generated bythe enumerators enums. A for comprehension for (enums ) yield e evaluatesexpression e for each binding generated by the enumerators enums and collects the results. An enumerator sequence always starts with a generator; this can be fol-lowed by further generators, value definitions, or guards. A generator p <- e pro-duces bindings from an expression e which is matched in some way against pat- tern p. A value definition p = e binds the value name p (or several names in apattern p) to the result of evaluating the expression e. A guard if e contains aboolean expression which restricts enumerated bindings. The precise meaning of generators and guards is defined by translation to invocations of four methods: map,withFilter, flatMap, and foreach. These methods can be implemented in differentways for different carrier types. The translation scheme is as follows. In a first step, every generator p <- e, wherep is not irrefutable (§8.1) for the type of e is replaced byp <- e.withFilter { case p => true; case _ => false } Then, the following rules are applied repeatedly until all comprehensions have beeneliminated.· Aforcomprehensionfor (p <- e ) yield eis translatedtoe.map { case p => e }.· A for loop for (p <- e ) e is translated to e.foreach { case p => e }.· A for comprehension------------------------------------------------------------------------------- 90Expressionsfor (p <- e; p <- e . . .) yield e,where . . . is a (possibly empty) sequence of generators, definitions, or guards,is translated to e.flatMap { case p => for (p <- e . . .) yield e} .· A for loopfor (p <- e; p <- e . . .) e.where . . . is a (possibly empty) sequence of generators, definitions, or guards, is translated toe.foreach { case p => for (p <- e . . .) e} .· A generator p <- e followed by a guard if g is translated to a single gen-erator p <- e.withFilter((x1, ..., xn) => g ) where x1, ..., xn are the free variables of p.· A generator p <- e followed by a value definition p = e is translated to thefollowing generator of pairs of values, where x and x are fresh names:(p, p ) <- for (x@p <- e) yield { val x @p = e ; (x, x ) } Example 6.19.1 The following code produces all pairs of numbers between 1 andn - 1 whose sums are prime.for{ i <- 1 until nj <- 1 until iif isPrime(i+j) } yield (i, j)The for comprehension is translated to:(1 until n).flatMap {case i => (1 until i).withFilter { j => isPrime(i+j) }.map { case j => (i, j) } } Example 6.19.2 For comprehensions can be used to express vector and matrix al-gorithms concisely. For instance, here is a function to compute the transpose of agiven matrix:def transpose[A](xss: Array[Array[A]]) = { for (i <- Array.range(0, xss(0) .length) ) yield-------------------------------------------------------------------------------6.20 Return Expressions91for (xs <- xss) yield xs(i) }Here is a function to compute the scalar product of two vectors:def scalprod(xs: Array[Double], ys: Array[Double]) = {var acc = 0.0for ((x, y) <- xs zip ys) acc = acc + x * y acc}Finally, here is a function to compute the product of two matrices. Compare withthe imperative version of Example 6.15.2.def matmul(xss: Array[Array[Double]], yss: Array[Array[Double]]) = { val ysst = transpose(yss)for (xs <- xss) yieldfor (yst <- ysst) yieldscalprod(xs, yst)}The code above makes use of the fact that map, flatMap, withFilter, and foreach are defined for instances of class scala.Array.6.20Return ExpressionsSyntax:Expr1::=`return' [Expr]A return expression return e must occur inside the body of some enclosing named method or function. The innermost enclosing named method or function in asource program, f , must have an explicitly declared result type, and the type of emust conform to it. The return expression evaluates the expression e and returns its value as the result of f . The evaluation of any statements or expressions followingthe return expression is omitted. The type of a return expression is scala.Nothing.The expression e may be omitted. The return expression return is type-checked and evaluated as if it was return () .An apply method which is generated by the compiler as an expansion of an anony-mous function does not count as a named function in the source program, and therefore is never the target of a return expression.Returning from a nested anonymous function is implemented by throwing andcatching a scala.runtime.NonLocalReturnControl.Any exception catches be- tween the point of return and the enclosing methods might see the exception. A-------------------------------------------------------------------------------92Expressionskey comparison makes sure that these exceptions are only caught by the method instance which is terminated by the return.If the return expression is itself part of an anonymous function, it is possible thatthe enclosing instance of f has already returned before the return expression is ex- ecuted. In that case, the thrown scala.runtime.NonLocalReturnControl will notbe caught, and will propagate up the call stack.6.21Throw ExpressionsSyntax:Expr1 ::=`throw' ExprA throw expression throw e evaluates the expression e. The type of this expressionmust conform to Throwable. If e evaluates to an exception reference, evaluation is aborted with the thrown exception. If e evaluates to null, evaluation is insteadaborted with a NullPointerException. If there is an active try expression (§6.22)which handles the thrown exception, evaluation resumes with the handler; other- wise the thread executing the throw is aborted. The type of a throw expression isscala.Nothing.6.22Try ExpressionsSyntax:Expr1 ::=`try' `{' Block `}' [`catch' `{' CaseClauses `}'] [`finally' Expr]A try expression is of the form try { b } catch h where the handler h is a patternmatching anonymous function (§8.5){ case p1 => b1 . . . case pn => bn } . This expression is evaluated by evaluating the block b. If evaluation of b does notcause an exception to be thrown, the result of b is returned. Otherwise the handlerh is applied to the thrown exception. If the handler contains a case matching the thrown exception, the first such case is invoked. If the handler contains no casematching the thrown exception, the exception is re-thrown.Let pt be the expected type of the try expression. The block b is ex-pected to conform to pt.The handler h is expected conform to typescala.PartialFunction[scala.Throwable, pt ]. The type of the try expression isthe weak least upper bound (§3.5.3) of the type of b and the result type of h. -------------------------------------------------------------------------------6.23 Anonymous Functions93A try expression try { b } finally e evaluates the block b. If evaluation of b does not cause an exception to be thrown, the expression e is evaluated. If an excep-tion is thrown during evaluation of e, the evaluation of the try expression is abortedwith the thrown exception. If no exception is thrown during evaluation of e, the result of b is returned as the result of the try expression.If an exception is thrown during evaluation of b, the finally block e is also evalu-ated. If another exception e is thrown during evaluation of e, evaluation of the try expression is aborted with the thrown exception. If no exception is thrown duringevaluation of e, the original exception thrown in b is re-thrown once evaluation of ehas completed. The block b is expected to conform to the expected type of the try expression. The finally expression e is expected to conform to type Unit.A try expressiontry { b } catch e1 finally e2is a shorthand fortry { try { b } catch e1 } finally e2. 6.23Anonymous FunctionsSyntax:Expr::=(Bindings | [`implicit'] id | `') `=>' ExprResultExpr::=(Bindings | ([`implicit'] id | `') `:' CompoundType) `=>' Block Bindings::=`(' Binding {`,' Binding} `) 'Binding::=(id | `') [`:' Type]The anonymous function (x1: T1, ..., xn: Tn) => e maps parameters xi of types Ti to a result given by expression e. The scope of each formal parameter xi is e.Formal parameters must have pairwise distinct names.Iftheexpectedtype oftheanonymousfunctionisoftheformscala.Functionn[S1, . . . , Sn, R ], the expected type of e is R and the type Tiof any of the parameters xi can be omitted, in which case Ti = Si is assumed. If the expected type of the anonymous function is some other type, all formal parametertypes must be explicitly given, and the expected type of e is undefined. The typeof the anonymous function is scala.Functionn[S1, ..., Sn, T ], where T is the packed type (§6.1) of e. T must be equivalent to a type which does not refer to anyof the formal parameters xi .The anonymous function is evaluated as the instance creation expression new scala.Functionn[T1, . . . , Tn, T ] {def apply(x1: T1, . . . , xn: Tn) : T = e}In the case of a single untyped formal parameter, (x ) => e can be abbreviated tox => e. If an anonymous function (x: T ) => e with a single typed parameter appears as the result expression of a block, it can be abbreviated to x: T => e.-------------------------------------------------------------------------------94Expressions A formal parameter may also be a wildcard represented by an underscore . In thatcase, a fresh name for the parameter is chosen arbitrarily.A named parameter of an anonymous function may be optionally preceded by an implicit modifier. In that case the parameter is labeled implicit (§7) ;howeverthe parameter section itself does not count as an implicit parameter section in thesense of (§7.2) .Hence, arguments to anonymous functions always have to be given explicitly.Example 6.23.1 Examples of anonymous functions:x => x// The identity functionf => g => x => f(g(x) )// Curried function composition (x: Int,y: Int) => x + y// A summation function() => { count += 1; count }// The function which takes an// empty parameter list () ,// increments a non-local variable // `count' and returns the new value._ => 5// The function that ignores its argument// and always returns 5.Placeholder Syntax for Anonymous FunctionsSyntax: SimpleExpr1::=`'An expression (of syntactic category Expr) may contain embedded underscore sym-bols _ at places where identifiers are legal. Such an expression represents an anony- mous function where subsequent occurrences of underscores denote successiveparameters.Define an underscore section to be an expression of the form :T where T is a type,or else of the form , provided the underscore does not appear as the expression part of a type ascription :T .An expression e of syntactic category Expr binds an underscore section u, if the fol-lowing two conditions hold: (1) e properly contains u, and (2) there is no other ex- pression of syntactic category Expr which is properly contained in e and which itselfproperly contains u.If an expression e binds underscore sections u1, ..., un, in this order, it is equivalent to the anonymous function (u , ... uresults from u1n ) => ewhere each uii byreplacing the underscore with a fresh identifier and e results from e by replacing -------------------------------------------------------------------------------6.24 Constant Expressions95each underscore section ui by u .iExample 6.23.2 The anonymous functions in the left column use placeholder syn- tax. Each of these is equivalent to the anonymous function on its right._ + 1x => x + 1_ * _(x1, x2) => x1 * x2(: Int) * 2(x: Int) => (x: Int) * 2 if () x else yz => if (z) x else y.map(f)x => x.map(f).map(_ + 1)x => x.map(y => y + 1)6.24Constant ExpressionsConstant expressions are expressions that the Scala compiler can evaluate to a con- stant. The definition of "constant expression" depends on the platform, but theyinclude at least the expressions of the following forms:· A literal of a value class, such as an integer · A string literal· A class constructed with Predef.classOf (§12.5)· An element of an enumeration from the underlying platform· A literal array, of the form Array(c1, ..., cn) , where all of the ci 's are themselves constant expressions· An identifier defined by a constant value definition (§4.1) .6.25StatementsSyntax:BlockStat::=Import| {Annotation} [`implicit'] Def|{Annotation} {LocalModifier} TmplDef|Expr1|TemplateStat ::=Import|{Annotation} {Modifier} Def |{Annotation} {Modifier} Dcl|Expr|-------------------------------------------------------------------------------96ExpressionsStatements occur as parts of blocks and templates. A statement can be an import, a definition or an expression, or it can be empty. Statements used in the templateof a class definition can also be declarations. An expression that is used as a state-ment can have an arbitrary value type. An expression statement e is evaluated by evaluating e and discarding the result of the evaluation.Block statements may be definitions which bind local names in the block. The onlymodifier allowed in all block-local definitions is implicit. When prefixing a class or object definition, modifiers abstract, final, and sealed are also permitted.Evaluation of a statement sequence entails evaluation of the statements in the orderthey are written.6.26 Implicit ConversionsImplicit conversions can be applied to expressions whose type does not match theirexpected type, to qualifiers in selections, and to unapplied methods. The available implicit conversions are given in the next two sub-sections.We say, a type T is compatible to a type U if T conforms to U after applying eta-expansion (§6.26.5) and view applications (§7.3) . 6.26.1 Value ConversionsThe following five implicit conversions can be applied to an expression e which hassome value type T and which is type-checked with some expected type pt.Overloading Resolution. If an expression denotes several possible members of aclass, overloading resolution (§6.26.3) is applied to pick a unique member.Type Instantiation.An expression e of polymorphic type [a1 >: L1 <: U1, . . . , an >: Ln <: Un]Twhich does not appear as the function part of a type application is converted to atype instance of T by determining with local type inference (§6.26.4) instance types T1, ..., Tn for the type variables a1, ..., an and implicitly embedding e in the typeapplication e[T1, ..., Tn] (§6.8) .Numeric Widening.If e has a primitive number type which weakly conforms (§3.5.3) to the expected type, it is widened to the expected type using one of thenumeric conversion methods toShort, toChar, toInt, toLong, toFloat, toDoubledefined in §12.2.1.------------------------------------------------------------------------------- 6.26 Implicit Conversions97Numeric Literal Narrowing.If the expected type is Byte, Short or Char, and theexpression e is an integer literal fitting in the range of that type, it is converted to the same literal in that type.Value Discarding.If e has some value type and the expected type is Unit, e is con-verted to the expected type by embedding it in the term { e; () }. View Application.If none of the previous conversions applies, and e's type doesnot conform to the expected type pt, it is attempted to convert e to the expectedtype with a view (§7.3) . Dynamic Member Selection.If none of the previous conversions applies, and e isa prefix of a selection e.x, and e's type conforms to class scala.Dynamic, then theselection is rewritten according to the rules for dynamic member selection (§??) . 6.26.2 Method ConversionsThe following four implicit conversions can be applied to methods which are notapplied to some argument list.Evaluation.A parameterless method m of type => T is always converted to type T by evaluating the expression to which m is bound.Implicit Application.If the method takes only implicit parameters, implicit argu-ments are passed following the rules of §7.2. Eta Expansion.Otherwise, if the method is not a constructor, and the expectedtype pt is a function type (Ts ) T , eta-expansion (§6.26.5) is performed on theexpression e.Empty Application. Otherwise, if e has method type () T , it is implicitly applied tothe empty argument list, yielding e() .6.26.3 Overloading ResolutionIf an identifier or selection e references several members of a class, the context of the reference is used to identify a unique member. The way this is done depends onwhether or not e is used as a function. Let A be the set of members referenced by e.Assume first that e appears as a function in an application, as in e(e1, ..., em) . -------------------------------------------------------------------------------98ExpressionsOne first determines the set of functions that is potentially applicable based on the shape of the arguments.The shape of an argument expression e, written shape(e) , is a type that is defined asfollows:· Forafunctionexpression (p1: T1, . . . , pn: Tn) => b:(Any , . . . , Any) => shape(b) , where Any occurs n times in the argumenttype.· For a named argument n = e: shape(e) .· For all other expressions: Nothing. Let B be the set of alternatives in A that are applicable (§6.6) to expressions(e1, ..., en) of types (shape(e1) , ..., shape(en) ). If there is precisely one alternativein B, that alternative is chosen. Otherwise, let S1, ..., Sm be the vector of types obtained by typing each argumentwith an undefined expected type. For every member m in B one determineswhether it is applicable to expressions (e1, ..., em) of types S1, ..., Sm. It is an error if none of the members in B is applicable. If there is one single applicable alterna-tive, that alternative is chosen. Otherwise, let C be the set of applicable alternativeswhich don't employ any default argument in the application to e1, ..., em. It is again an error if C is empty. Otherwise, one chooses the most specific alternative amongthe alternatives in C , according to the following definition of being "as specific as",and "more specific than": · A parameterized method m of type (p1 : T1, ..., pn : Tn) U is as specific as someother member m of type S if m is applicable to arguments (p1, ..., pn ) oftypes T1, ..., Tn.· A polymorphic method of type [a1 >: L1 <: U1, ..., an >: Ln <: Un]T is as specific as some other member of type S if T is as specific as S under theassumption that for i = 1, ..., n each ai is an abstract type name boundedfrom below by Li and from above by Ui . · A member of any other type is always as specific as a parameterized methodor a polymorphic method.· Given two members of types T and U which are neither param-eterized nor polymorphic method types, the member of type T is as specific as the member of type U if the existential dual of Tconforms to the existential dual of U .Here, the existential dualof a polymorphic type[a1 >: L1 <: U1, . . . , an >: Ln <: Un]T isT forSome { type a1 >: L1 <: U1 , ..., type an >: Ln <: Un}. The ex-istential dual of every other type is the type itself.------------------------------------------------------------------------------- 6.26 Implicit Conversions99The relative weight of an alternative A over an alternative B is a number from 0 to 2,defined as the sum of· 1 if A is as specific as B , 0 otherwise, and · 1 if A is defined in a class or object which is derived from the class or objectdefining B , 0 otherwise.A class or object C is derived from a class or object D if one of the following holds: · C is a subclass of D, or· C is a companion object of a class derived from D, or· D is a companion object of a class from which C is derived.An alternative A is more specific than an alternative B if the relative weight of A over B is greater than the relative weight of B over A.It is an error if there is no alternative in C which is more specific than all otheralternatives in C .Assume next that e appears as a function in a type application, as in e[targs ]. Then all alternatives in A which take the same number of type parameters as there aretype arguments in targs are chosen. It is an error if no such alternative exists. Ifthere are several such alternatives, overloading resolution is applied again to the whole expression e[targs ].Assume finally that e does not appear as a function in either an application or a typeapplication. If an expected type is given, let B be the set of those alternatives in A which are compatible (§6.26) to it. Otherwise, let B be the same as A . We choosein this case the most specific alternative among all alternatives in B. It is an error ifthere is no alternative in B which is more specific than all other alternatives in B. Example 6.26.1 Consider the following definitions:class A extends B {}def f(x: B, y: B) = . . .def f(x: A, y: B) = . . .val a: Aval b: BThen the application f(b, b) refers to the first definition of f whereas the applica- tion f(a, a) refers to the second. Assume now we add a third overloaded definitiondef f(x: B, y: A) = . . .Then the application f(a, a) is rejected for being ambiguous, since no most spe- cific applicable signature exists.-------------------------------------------------------------------------------100Expressions6.26.4 Local Type InferenceLocal type inference infers type arguments to be passed to expressions of polymor- phic type. Say e is of type [a1 >: L1 <: U1, ..., an >: Ln <: Un]T and no explicit typeparameters are given.Local type inference converts this expression to a type application e[T1, ..., Tn]. The choice of the type arguments T1, ..., Tn depends on the context in which theexpression appears and on the expected type pt. There are three cases.Case 1: Selections.If the expression appears as the prefix of a selection with a name x, then type inference is deferred to the whole expression e.x. That is, if e.xhas type S, it is now treated as having type [a1 >: L1 <: U1, ..., an >: Ln <: Un]S, andlocal type inference is applied in turn to infer type arguments for a1, ..., an, using the context in which e.x appears.Case 2: Values.If the expression e appears as a value without being applied tovalue arguments, the type arguments are inferred by solving a constraint system which relates the expression's type T with the expected type pt. Without loss ofgenerality we can assume that T is a value type; if it is a method type we applyeta-expansion (§6.26.5) to convert it to a function type. Solving means finding a substitution of types Ti for the type parameters ai such that· None of inferred types Ti is a singleton type §3.2.1· All type parameter bounds are respected, i.e. Li <: ai and ai <: Ui for i = 1, ..., n.· The expression's type conforms to the expected type, i.e. T <: pt.It is a compile time error if no such substitution exists. If several substitutions exist,local-type inference will choose for each type variable ai a minimal or maximal type Ti of the solution space. A maximal type Ti will be chosen if the type parameter aiappears contravariantly (§4.5) in the type T of the expression. A minimal type Tiwill be chosen in all other situations, i.e. if the variable appears covariantly, non- variantly or not at all in the type T . We call such a substitution an optimal solutionof the given constraint system for the type T .Case 3: Methods.The last case applies if the expression e appears in an applica- tion e(d1, ..., dm) . In that case T is a method type (p1 : R1, ..., pm : Rm) T . With-out loss of generality we can assume that the result type T is a value type; if it is amethod type we apply eta-expansion (§6.26.5) to convert it to a function type. One computes first the types S j of the argument expressions d j , using two alternativeschemes. Each argument expression d j is typed first with the expected type R j , inwhich the type parameters a1, ..., an are taken as type constants. If this fails, the -------------------------------------------------------------------------------6.26 Implicit Conversions101argument d j is typed instead with an expected type R which results from R jj byreplacing every type parameter in a1, ..., an with undefined.In a second step, type arguments are inferred by solving a constraint systemwhich relates the method's type with the expected type pt and the argument types S1, ..., Sm. Solving the constraint system means finding a substitution of types Tifor the type parameters ai such that· None of inferred types Ti is a singleton type §3.2.1· All type parameter bounds are respected, i.e. Li <: ai and ai <: Ui for i = 1, ..., n.· The method's result type T conforms to the expected type, i.e. T <: pt.· Each argument type weakly conforms (§3.5.3) to the corresponding formalparameter type, i.e. S j <:w R j for j = 1, ..., m. It is a compile time error if no such substitution exists. If several solutions exist, anoptimal one for the type T is chosen.All or parts of an expected type pt may be undefined. The rules for conformance (§3.5.2) are extended to this case by adding the rule that for any type T the followingtwo statements are always true:undefined <: TandT <: undefined.It is possible that no minimal or maximal solution for a type variable exists, in which case a compile-time error results. Because <: is a pre-order, it is also possible that asolution set has several optimal solutions for a type. In that case, a Scala compiler isfree to pick any one of them. Example 6.26.2 Consider the two methods:def cons[A](x: A, xs: List[A]) : List[A] = x :: xsdef nil[B]: List[B] = Niland the definitionval xs = cons(1, nil) .The application of cons is typed with an undefined expected type. This application is completed by local type inference to cons[Int](1, nil) . Here, one uses thefollowing reasoning to infer the type argument Int for the type parameter a:First, the argument expressions are typed. The first argument 1 has type Int whereas the second argument nil is itself polymorphic. One tries to type-checknil with an expected type List[a]. This leads to the constraint systemList[b?] <: List[a]------------------------------------------------------------------------------- 102Expressionswhere we have labeled b? with a question mark to indicate that it is a variable inthe constraint system. Because class List is covariant, the optimal solution of this constraint isb = scala.Nothing .In a second step, one solves the following constraint system for the type parametera of cons:Int <: a?List[scala.Nothing] <: List[a?] List[a?] <: undefinedThe optimal solution of this constraint system isa = Int ,so Int is the type inferred for a.Example 6.26.3 Consider now the definitionval ys = cons("abc", xs) where xs is defined of type List[Int] as before. In this case local type inferenceproceeds as follows.First, the argument expressions are typed. The first argument "abc" has type String.The second argument xs is first tried to be typed with expected typeList[a]. This fails, as List[Int] is not a subtype of List[a]. Therefore, the sec-ond strategy is tried; xs is now typed with expected type List[undefined]. This succeeds and yields the argument type List[Int].In a second step, one solves the following constraint system for the type parametera of cons:String <: a?List[Int] <: List[a?] List[a?] <: undefinedThe optimal solution of this constraint system isa = scala.Any ,so scala.Any is the type inferred for a.6.26.5 Eta ExpansionEta-expansion converts an expression of method type to an equivalent expression of function type. It proceeds in two steps.-------------------------------------------------------------------------------6.26 Implicit Conversions103First, one identifes the maximal sub-expressions of e; let's say these are e1, ..., em. For each of these, one creates a fresh name xi . Let e be the expression resultingfrom replacing every maximal subexpression ei in e by the corresponding freshname xi . Second, one creates a fresh name yi for every argument type Ti of the method (i = 1, ..., n) . The result of eta-conversion is then:{ val x1 = e1;. . .val xm = em;(y1 : T1, . . . , yn : Tn) => e (y1, . . . , yn)}------------------------------------------------------------------------------- -------------------------------------------------------------------------------Chapter 7Implicit Parameters and Views7.1The Implicit ModifierSyntax:LocalModifier ::= `implicit'ParamClauses::= {ParamClause} [nl] `(' `implicit' Params `) 'Template members and parameters labeled with an implicit modifier can bepassed to implicit parameters (§7.2) and can be used as implicit conversions called views (§7.3) .The implicit modifier is illegal for all type members, as well as fortop-level (§9.2) objects.Example 7.1.1 The following code defines an abstract class of monoids and two concrete implementations, StringMonoid and IntMonoid. The two implementa-tions are marked implicit.abstract class Monoid[A] extends SemiGroup[A] {def unit: Adef add(x: A, y: A) : A }object Monoids {implicit object stringMonoid extends Monoid[String] {def add(x: String, y: String) : String = x.concat(y)def unit: String = ""} implicit object intMonoid extends Monoid[Int] {def add(x: Int, y: Int) : Int = x + ydef unit: Int = 0}}------------------------------------------------------------------------------- 106Implicit Parameters and Views7.2Implicit ParametersAn implicit parameter list (implicit p1,...,pn) of a method marks the param-eters p1, ..., pn as implicit. A method or constructor can have only one implicit parameter list, and it must be the last parameter list given.A method with implicit parameters can be applied to arguments just like a normalmethod. In this case the implicit label has no effect. However, if such a method misses arguments for its implicit parameters, such arguments will be automaticallyprovided.The actual arguments that are eligible to be passed to an implicit parameter of typeT fall into two categories. First, eligible are all identifiers x that can be accessed at the point of the method call without a prefix and that denote an implicit definition(§7.1) or an implicit parameter. An eligible identifier may thus be a local name, or amember of an enclosing template, or it may be have been made accessible without a prefix through an import clause (§4.7) .If there are no eligible identifiers underthis rule, then, second, eligible are also all implicit members of some object thatbelongs to the implicit scope of the implicit parameter's type, T . The implicit scope of a type T consists of all companion modules (§5.4) of classesthat are associated with the implicit parameter's type. Here, we say a class C is asso-ciated with a type T , if it is a base class (§5.1.2) of some part of T . The parts of a type T are:· if T is a compound type T1 with ... with Tn, the union of the parts ofT1, ..., Tn, as well as T itself,· if T is a parameterized type S[T1, ..., Tn], the union of the parts of S and T1, ..., Tn,· if T is a singleton type p.type, the parts of the type of p,· if T is a type projection S#U , the parts of S as well as T itself,· in all other cases, just T itself. If there are several eligible arguments which match the implicit parameter's type,a most specific one will be chosen using the rules of static overloading resolution(§6.26.3) .If the parameter has a default argument and no implicit argument can be found the default argument is used.Example 7.2.1 Assuming the classes from Example 7.1.1,here is a method whichcomputes the sum of a list of elements using the monoid's add and unit operations. def sum[A](xs: List[A]) (implicit m: Monoid[A]) : A =if (xs.isEmpty) m.unitelse m.add(xs.head, sum(xs.tail) )------------------------------------------------------------------------------- 7.2 Implicit Parameters107The monoid in question is marked as an implicit parameter, and can therefore beinferred based on the type of the list. Consider for instance the call sum(List(1, 2, 3) )in a context where stringMonoid and intMonoid are visible. We know that the formaltype parameter a of sum needs to be instantiated to Int. The only eligible objectwhich matches the implicit formal parameter type Monoid[Int] is intMonoid so this object will be passed as implicit parameter.This discussion also shows that implicit parameters are inferred after any type ar-guments are inferred (§6.26.4) .Implicit methods can themselves have implicit parameters. An example is the fol- lowing method from module scala.List, which injects lists into the scala.Orderedclass, provided the element type of the list is also convertible to this type.implicit def list2ordered[A](x: List[A]) (implicit elem2ordered: A => Ordered[A]) : Ordered[List[A]] =...Assume in addition a methodimplicit def int2ordered(x: Int) : Ordered[Int]that injects integers into the Ordered class. We can now define a sort method over ordered lists:def sort[A](xs: List[A]) (implicit a2ordered: A => Ordered[A]) = ...We can apply sort to a list of lists of integers yss: List[List[Int]] as follows:sort(yss) The call above will be completed by passing two nested implicit arguments:sort(yss) (xs: List[Int] => list2ordered[Int](xs) (int2ordered) ) .The possibility of passing implicit arguments to implicit arguments raises the pos- sibility of an infinite recursion. For instance, one might try to define the followingmethod, which injects every type into the Ordered class:implicit def magic[A](x: A) (implicit a2ordered: A => Ordered[A]) : Ordered[A] = a2ordered(x)Now, if one tried to apply sort to an argument arg of a type that did not have an-other injection into the Ordered class, one would obtain an infinite expansion:sort(arg) (x => magic(x) (x => magic(x) (x => ... ) )) -------------------------------------------------------------------------------108Implicit Parameters and ViewsTo prevent such infinite expansions, the compiler keeps track of a stack of "open implicit types" for which implicit arguments are currently being searched. When-ever an implicit argument for type T is searched, the "core type" of T is added to thestack. Here, the core type of T is T with aliases expanded, top-level type annotations (§11) and refinements (§3.2.7) removed, and occurrences of top-level existentiallybound variables replaced by their upper bounds. The core type is removed from thestack once the search for the implicit argument either definitely fails or succeeds. Everytime a core type is added to the stack, it is checked that this type does notdominate any of the other types in the set.Here, a core type T dominates a type U if T is equivalent (§3.5.1) to U , or if the top- level type constructors of T and U have a common element and T is more complexthan U .The set of top-level type constructors ttcs(T ) of a type T depends on the form of thetype: For a type designator,ttcs(p.c) = {c};For a parameterized type,ttcs(p.c[targs]) = {c};For a singleton type,ttcs(p.t y pe) = ttcs(T ) , provided p has type T ; For a compound type,ttcs(T1 with ... with Tn) = ttcs(T1) ... ttcs(Tn) .The complexity complexity(T ) of a core type is an integer which also depends on theform of the type: For a type designator,complexity(p.c) = 1 + complexity(p)For a parameterized type,complexity(p.c[targs]) = 1 + complexity(targs)For a singleton type denoting a package p, complexity(p.t y pe) = 0For any other singleton type,complexity(p.t y pe) = 1 + complexity(T ) , provided p has type T ;For a compound type,complexity(T1 with ... with Tn) = complexity(Ti ) Example 7.2.2 Whentypingsort(xs)forsomelistxsoftypeList[List[List[Int]]], the sequence of types for which implicit arguments are searched isList[List[Int]] => Ordered[List[List[Int]]],List[Int] => Ordered[List[Int]]Int => Ordered[Int]------------------------------------------------------------------------------- 7.3 Views109All types share the common type constructor scala.Function1, but the complexityof the each new type is lower than the complexity of the previous types. Hence, the code typechecks.Example 7.2.3 Let ys be a list of some type which cannot be converted to Ordered.For instance:val ys = List(new IllegalArgumentException, new ClassCastException, new Error) Assume that the definition of magic above is in scope. Then the sequence of typesfor which implicit arguments are searched isThrowable => Ordered[Throwable],Throwable => Ordered[Throwable], ...Since the second type in the sequence is equal to the first, the compiler will issue anerror signalling a divergent implicit expansion.7.3ViewsImplicit parameters and methods can also define implicit conversions called views. A view from type S to type T is defined by an implicit value which has function typeS=>T or (=>S) =>T or by a method convertible to a value of that type.Views are applied in three situations. 1. If an expression e is of type T , and T does not conform to the expression'sexpected type pt. In this case an implicit v is searched which is applicable toe and whose result type conforms to pt. The search proceeds as in the case of implicit parameters, where the implicit scope is the one of T => pt. If such aview is found, the expression e is converted to v(e) .2. In a selection e.m with e of type T , if the selector m does not denote a member of T . In this case, a view v is searched which is applicable to e and whose resultcontains a member named m. The search proceeds as in the case of implicitparameters, where the implicit scope is the one of T . If such a view is found, the selection e.m is converted to v(e) .m.3. In a selection e.m(args) with e of type T , if the selector m denotes some mem-ber(s) of T , but none of these members is applicable to the arguments args. In this case a view v is searched which is applicable to e and whose result con-tains a method m which is applicable to args. The search proceeds as in thecase of implicit parameters, where the implicit scope is the one of T . If such a view is found, the selection e.m is converted to v(e) .m(args) .-------------------------------------------------------------------------------110Implicit Parameters and Views The implicit view, if it is found, can accept is argument e as a call-by-value or asa call-by-name parameter. However, call-by-value implicits take precedence overcall-by-name implicits.As for implicit parameters, overloading resolution is applied if there are several pos- sible candidates (of either the call-by-value or the call-by-name category) .Example 7.3.1 Class scala.Ordered[A] contains a methoddef <= [B >: A](that: B) (implicit b2ordered: B => Ordered[B]) : Boolean . Assume two lists xs and ys of type List[Int] and assume that the list2orderedand int2ordered methods defined in §7.2are in scope. Then the operationxs <= ysis legal, and is expanded to: list2ordered(xs) (int2ordered) .<=(ys)(xs => list2ordered(xs) (int2ordered) )The first application of list2ordered converts the list xs to an instance of classOrdered, whereas the second occurrence is part of an implicit parameter passed to the <= method.7.4Context Bounds and View BoundsSyntax:TypeParam ::= (id | `') [TypeParamClause] [`>:' Type] [`<:'Type]{`<%' Type} {`:' Type} A type parameter A of a method or non-trait class may have one or more viewbounds A <% T . In this case the type parameter may be instantiated to any typeS which is convertible by application of a view to the bound T . A type parameter A of a method or non-trait class may also have one or more con-text bounds A : T . In this case the type parameter may be instantiated to any typeS for which evidence exists at the instantiation point that S satisfies the bound T . Such evidence consists of an implicit value with type T [S].A method or class containing type parameters with view or context bounds istreated as being equivalent to a method with implicit parameters. Consider first the case of a single parameter with view and/or context bounds such as:def f [A <% T1 ... <% Tm : U1 : Un](ps) : R = ...------------------------------------------------------------------------------- 7.5 Manifests111Then the method definition above is expanded todef f [A](ps) (implicit v1: A => T1, ..., vm: A => Tm,w1: U1[A], ..., wn: Un[A]) : R = ...where the vi and w j are fresh names for the newly introduced implicit parameters. These parameters are called evidence parameters.If a class or method has several view- or context-bounded type parameters, eachsuch type parameter is expanded into evidence parameters in the order they appear and all the resulting evidence parameters are concatenated in one implicit param-eter section. Since traits do not take constructor parameters, this translation doesnot work for them. Consequently, type-parameters in traits may not be view- or context-bounded.Example 7.4.1 The <= method mentioned in Example 7.3.1can be declared moreconcisely as follows:def <= [B >: A <% Ordered[B]](that: B) : Boolean A method or class may define implicit parameters in addition to view- or contextbounds. In this case the implicit parameters are appended to the implicit parametersection of the evidence parameters. Example 7.4.2 Consider the following method definition:def f[A: Manifest](x: A) (implicit y: B) : RThen the method definition above is expanded to:def f[A](x: A) (implicit z: Manifest[A], y: B) : R 7.5ManifestsManifests are type descriptors that can be automatically generated by the Scalacompiler as arguments to implicit parameters. The Scala standard library contains a hierarchy of four manifest classes, with OptManifest at the top. Their signaturesfollow the outline below.trait OptManifest[+T]object NoManifest extends OptManifest[Nothing]trait ClassManifest[T] extends OptManifest[T] trait Manifest[T] extends ClassManifest[T]If an implicit parameter of a method or constructor is of a subtype M [T ] of classOptManifest[T], a manifest is determined for M [S], according to the following rules. -------------------------------------------------------------------------------112Implicit Parameters and ViewsFirst if there is already an implicit argument that matches M [T ], this argument is selected.Otherwise, let Mobj be the companion object scala.reflect.Manifest if M is traitManifest, or be the companion object scala.reflect.ClassManifest otherwise.Let M be the trait Manifest if M is trait Manifest, or be the trait OptManifest oth- erwise. Then the following rules apply.1. If T is a value class or one of the classes Any, AnyVal, Object, Null, or Nothing,a manifest for it is generated by selecting the corresponding manifest value Manifest.T , which exists in the Manifest module.2. If T is an instance of Array[S], a manifest is generated with the invocationMobj.arrayType[S](m) , where m is the manifest determined for M [S]. 3. If T is some other class type S#C [U1, ..., Un] where the prefix type S can-not be statically determined from the class C , a manifest is generated withthe invocation Mobj.classType[T](m0, classOf[T], ms) where m0 is the manifest determined for M [S] and ms are the manifests determined forM [U1], ..., M [Un].4. If T is some other class type with type arguments U1, ..., Un, a manifest isgenerated with the invocation Mobj.classType[T](classOf[T], ms) where ms are the manifests determined for M [U1], ..., M [Un].5. If T is a singleton type p.type, a manifest is generated with the invocationMobj.singleType[T](p)6. If T is a refined type T {R}, a manifest is generated for T . (That is, refinements are never reflected in manifests) .7. If T is an intersection type T1 with , ..., with Tn where n > 1, the re-sult depends on whether a full manifest is to be determined or not.If M is trait Manifest, then a manifest is generated with the invocationManifest.intersectionType[T](ms) where ms are the manifests deter-mined for M [T1], ..., M[Tn]. Otherwise, if M is trait ClassManifest, then a manifest is generated for the intersection dominator (§3.7) of the typesT1, ..., Tn.8. If T is some other type, then if M is trait OptManifest, a manifest is generatedfrom the designator scala.reflect.NoManifest. If M is a type different from OptManifest, a static error results.-------------------------------------------------------------------------------Chapter 8Pattern Matching8.1Patterns Syntax:Pattern::=Pattern1 { `|' Pattern1 }Pattern1::=varid `:' TypePat|`' `:' TypePat|Pattern2 Pattern2::=varid [`@' Pattern3]|Pattern3Pattern3::=SimplePattern|SimplePattern {id [nl] SimplePattern} SimplePattern::=`'|varid|Literal|StableId|StableId `(' [Patterns] `) '|StableId `(' [Patterns `,'] [varid `@'] `' `*' `) ' |`(' [Patterns] `) '|XmlPatternPatterns::=Pattern {`,' Patterns}A pattern is built from constants, constructors, variables and type tests. Pattern matching tests whether a given value (or sequence of values) has the shape definedby a pattern, and, if it does, binds the variables in the pattern to the correspondingcomponents of the value (or sequence of values) . The same variable name may not be bound more than once in a pattern.Example 8.1.1 Some examples of patterns are:1. The pattern ex: IOException matches all instances of class IOException,------------------------------------------------------------------------------- 114Pattern Matchingbinding variable ex to the instance.2. The pattern Some(x) matches values of the form Some(v) , binding x to theargument value v of the Some constructor. 3. The pattern (x, ) matches pairs of values, binding x to the first componentof the pair. The second component is matched with a wildcard pattern.4. The pattern x :: y :: xs matches lists of length 2, binding x to the list's first element, y to the list's second element, and xs to the remainder.5. The pattern 1 | 2 | 3 matches the integers between 1 and 3.Pattern matching is always done in a context which supplies an expected type of the pattern. We distinguish the following kinds of patterns.8.1.1 Variable PatternsSyntax:SimplePattern::=`'|varidA variable pattern x is a simple identifier which starts with a lower case letter. It matches any value, and binds the variable name to that value. The type of x is theexpected type of the pattern as given from outside. A special case is the wild-cardpattern _ which is treated as if it was a fresh variable on each occurrence. 8.1.2 Typed PatternsSyntax:Pattern1::=varid `:' TypePat|`' `:' TypePatA typed pattern x : T consists of a pattern variable x and a type pattern T . The type of x is the type pattern T , where each type variable and wildcard is replaced by afresh, unknown type. This pattern matches any value matched by the type patternT (§8.2) ;it binds the variable name to that value. 8.1.3 Pattern BindersSyntax:Pattern2::=varid `@' Pattern3A pattern binder x@p consists of a pattern variable x and a pattern p. The type ofthe variable x is the static type T of the pattern p. This pattern matches any value v matched by the pattern p, provided the run-time type of v is also an instance of T ,and it binds the variable name to that value.------------------------------------------------------------------------------- 8.1 Patterns1158.1.4 Literal PatternsSyntax:SimplePattern::=LiteralA literal pattern L matches any value that is equal (in terms of ==) to the literal L. The type of L must conform to the expected type of the pattern.8.1.5 Stable Identifier PatternsSyntax:SimplePattern::=StableIdA stable identifier pattern is a stable identifier r (§3.1) .The type of r must conform to the expected type of the pattern. The pattern matches any value v such thatr == v (§12.1) .To resolve the syntactic overlap with a variable pattern, a stable identifier patternmay not be a simple name starting with a lower-case letter. However, it is possible to enclose a such a variable name in backquotes; then it is treated as a stable identifierpattern.Example 8.1.2 Consider the following function definition:def f(x: Int, y: Int) = x match { case y => ...}Here, y is a variable pattern, which matches any value. If we wanted to turn thepattern into a stable identifier pattern, this can be achieved as follows:def f(x: Int, y: Int) = x match { case `y` => ...}Now, the pattern matches the y parameter of the enclosing function f. That is, thematch succeeds only if the x argument and the y argument of f are equal. 8.1.6 Constructor PatternsSyntax:SimplePattern::=StableId `(' [Patterns] `)A constructor pattern is of the form c(p1, ..., pn) where n 0. It consists of a stable identifier c, followed by element patterns p1, ..., pn. The constructor c is a simple-------------------------------------------------------------------------------116Pattern Matching or qualified name which denotes a case class (§5.3.2) .If the case class is monomor-phic, then it must conform to the expected type of the pattern, and the formal pa-rameter types of x's primary constructor (§5.3) are taken as the expected types of the element patterns p1, ..., pn. If the case class is polymorphic, then its type parame-ters are instantiated so that the instantiation of c conforms to the expected type ofthe pattern. The instantiated formal parameter types of c's primary constructor are then taken as the expected types of the component patterns p1, ..., pn. The patternmatches all objects created from constructor invocations c(v1, ..., vn) where eachelement pattern pi matches the corresponding value vi . A special case arises when c's formal parameter types end in a repeated parameter.This is further discussed in (§8.1.9) .8.1.7 Tuple PatternsSyntax:SimplePattern ::=`(' [Patterns] `) 'Atuplepattern(p1, . . . , pn)isanaliasfortheconstructorpattern scala.Tuplen(p1, . . . , pn) , where n 2.The empty tuple () is the uniquevalue of type scala.Unit.8.1.8 Extractor PatternsSyntax:SimplePattern::= StableId `(' [Patterns] `) 'An extractor pattern x(p1, ..., pn) where n 0 is of the same syntactic form as aconstructor pattern. However, instead of a case class, the stable identifier x denotes an object which has a member method named unapply or unapplySeq that matchesthe pattern.An unapply method in an object x matches the pattern x(p1, ..., pn) if it takes exactlyone argument and one of the following applies: n = 0 and unapply's result type is Boolean. In this case the extractor patternmatches all values v for which x.unapply(v) yields true.n = 1 and unapply's result type is Option[T ], for some type T . In this case, the (only) argument pattern p1 is typed in turn with expected type T . Theextractor pattern matches then all values v for which x.unapply(v) yields avalue of form Some(v1) , and p1 matches v1. n > 1 and unapply's result type is Option[(T1, ..., Tn) ], for some typesT1, ..., Tn. In this case, the argument patterns p1, ..., pn are typed in turnwith expected types T1, ..., Tn. The extractor pattern matches then all values -------------------------------------------------------------------------------8.1 Patterns117v for which x.unapply(v) yields a value of form Some((v1, ..., vn) ), and each pattern pi matches the corresponding value vi .An unapplySeq method in an object x matches the pattern x(p1, ..., pn) if it takesexactly one argument and its result type is of the form Option[S], where S is a sub- type of Seq[T ] for some element type T . This case is further discussed in (§8.1.9) .Example 8.1.3 The Predef object contains a definition of an extractor object Pair:object Pair {def apply[A, B](x: A, y: B) = Tuple2(x, y) def unapply[A, B](x: Tuple2[A, B]) : Option[Tuple2[A, B]] = Some(x)}This means that the name Pair can be used in place of Tuple2 for tuple formationas well as for deconstruction of tuples in patterns. Hence, the following is possible: val x = (1, 2)val y = x match {case Pair(i, s) => Pair(s + i, i * i)}8.1.9 Pattern SequencesSyntax:SimplePattern ::= StableId `(' [Patterns `,'] [varid `@'] `' `*' `) ' A pattern sequence p1, ..., pn appears in two contexts. First, in a constructor pat-tern c(q1, ..., qm, p1, ..., pn) , where c is a case class which has m + 1 primary con-structor parameters, ending in a repeated parameter (§4.6.2) of type S. Second, in an extractor pattern x(p1, ..., pn) if the extractor object x has an unapplySeqmethod with a result type conforming to Seq[S], but does not have an unapplymethod that matches p1, ..., pn. The expected type for the pattern sequence is in each case the type S.The last pattern in a pattern sequence may be a sequence wildcard *. Each ele-ment pattern pi is type-checked with S as expected type, unless it is a sequencewildcard. If a final sequence wildcard is present, the pattern matches all values v that are sequences which start with elements matching patterns p1, ..., pn-1. If nofinal sequence wildcard is given, the pattern matches all values v that are sequencesof length n which consist of elements matching patterns p1, ..., pn. 8.1.10 Infix Operation PatternsSyntax:-------------------------------------------------------------------------------118Pattern MatchingPattern3::= SimplePattern {id [nl] SimplePattern}An infix operation pattern p op q is a shorthand for the constructor or extractorpattern op(p, q) . The precedence and associativity of operators in patterns is the same as in expressions (§6.12) .An infix operation pattern p op (q1, ..., qn) is a shorthand for the constructor orextractor pattern op(p, q1, ..., qn) .8.1.11 Pattern Alternatives Syntax:Pattern::=Pattern1 { `|' Pattern1 }A pattern alternative p1 | ... | pn consists of a number of alternative patternspi . All alternative patterns are type checked with the expected type of the pattern. They may no bind variables other than wildcards. The alternative pattern matchesa value v if at least one its alternatives matches v.8.1.12 XML PatternsXML patterns are treated in §10.2. 8.1.13 Regular Expression PatternsRegular expression patterns have been discontinued in Scala from version 2.0.Later version of Scala provide a much simplified version of regular expression pat- terns that cover most scenarios of non-text sequence processing. A sequence patternis a pattern that stands in a position where either (1) a pattern of a type T which isconforming to Seq[A] for some A is expected, or (2) a case class constructor that has an iterated formal parameter A*. A wildcard star pattern * in the rightmost positionstands for arbitrary long sequences. It can be bound to variables using @, as usual,in which case the variable will have the type Seq[A]. 8.1.14 Irrefutable PatternsA pattern p is irrefutable for a type T , if one of the following applies:1. p is a variable pattern,2. p is a typed pattern x : T , and T <: T , 3. p is a constructor pattern c(p1, ..., pn) , the type T is an instance of class c, theprimary constructor (§5.3) of type T has argument types T1, ..., Tn, and eachpi is irrefutable for Ti . -------------------------------------------------------------------------------8.2 Type Patterns1198.2Type PatternsSyntax:TypePat::=Type Type patterns consist of types, type variables, and wildcards. A type pattern T is ofone of the following forms:· A reference to a class C , p.C , or T #C . This type pattern matches any non-null instance of the given class. Note that the prefix of the class, if it is given, is rel-evant for determining class instances. For instance, the pattern p.C matchesonly instances of classes C which were created with the path p as prefix. The bottom types scala.Nothing and scala.Null cannot be used as type pat-terns, because they would match nothing in any case.· A singleton type p.type. This type pattern matches only the value denoted by the path p (that is, a pattern match involved a comparison of the matchedvalue with p using method eq in class AnyRef) .· A compound type pattern T1 with ... with Tn where each Ti is a type pat- tern. This type pattern matches all values that are matched by each of the typepatterns Ti .· A parameterized type pattern T [a1, ..., an], where the ai are type variable pat-terns or wildcards . This type pattern matches all values which match T for some arbitrary instantiation of the type variables and wildcards. The boundsor alias type of these type variable are determined as described in (§8.3) .· A parameterized type pattern scala.Array[T1], where T1 is a type pattern. This type pattern matches any non-null instance of type scala.Array[U1],where U1 is a type matched by T1.Types which are not of one of the forms described above are also accepted as type patterns. However, such type patterns will be translated to their erasure (§3.7) .TheScala compiler will issue an "unchecked" warning for these patterns to flag the pos-sible loss of type-safety. A type variable pattern is a simple identifier which starts with a lower case letter.However, the predefined primitive type aliases unit, boolean, byte, short, char,int, long, float, and double are not classified as type variable patterns. 8.3Type Parameter Inference in PatternsType parameter inference is the process of finding bounds for the bound type vari-ables in a typed pattern or constructor pattern. Inference takes into account the expected type of the pattern.-------------------------------------------------------------------------------120Pattern MatchingType parameter inference for typed patterns.. Assume a typed pattern p : T . LetT result from T where all wildcards in T are renamed to fresh variable names. Leta1, ..., an be the type variables in T . These type variables are considered bound in the pattern. Let the expected type of the pattern be pt.Type parameter inference constructs first a set of subtype constraints over the typevariables ai . The initial constraints set C0 reflects just the bounds of these type vari- ables. That is, assuming T has bound type variables a1, ..., an which correspondto class type parameters a , . . . , a1n with lower bounds L1, . . . , Ln and upper boundsU1, ..., Un, C0 contains the constraints ai <: Ui(i = 1, ..., n)Li <: ai(i = 1, ..., n)where is the substitution [a :1 = a1, . . . , an := an ].The set C0 is then augmented by further subtype constraints. There are two cases. Case 1:.If there exists a substitution over the type variables ai , ..., an such thatT conforms to pt, one determines the weakest subtype constraints C1 over thetype variables a1, ..., an such that C0  C1 implies that T conforms to pt. Case 2:.Otherwise, if T can not be made to conform to pt by instantiating its typevariables, one determines all type variables in pt which are defined as type param-eters of a method enclosing the pattern. Let the set of such type parameters be b1, ..., bm. Let C be the subtype constraints reflecting the bounds of the type vari-0ables bi . If T denotes an instance type of a final class, let C2 be the weakest setof subtype constraints over the type variables a1, ..., an and b1, ..., bm such that C0  C0  C2 implies that T conforms to pt. If T does not denote an instance typeof a final class, let C2 be the weakest set of subtype constraints over the type vari-ables a1, ..., an and b1, ..., bm such that C0  C0  C2 implies that it is possible to construct a type T which conforms to both T and pt. It is a static error if there is nosatisfiable set of constraints C2 with this property.The final step consists in choosing type bounds for the type variables which imply the established constraint system. The process is different for the two cases above.Case 1:.We take ai >: Li <: Ui where each Li is minimal and each Ui is maximalwrt <: such that ai >: Li <: Ui for i = 1, ..., n implies C0  C1. Case 2:.We take ai >: Li <: Ui and bi >: Lwhere each Lis minimali <: Uii and L jand each Ui and U is maximal such that aj i >: Li <: Ui for i = 1, . . . , n and b j >:Lfor jj <: U j= 1, . . . , m implies C0  C0  C2.------------------------------------------------------------------------------- 8.3 Type Parameter Inference in Patterns121In both cases, local type inference is permitted to limit the complexity of inferredbounds. Minimality and maximality of types have to be understood relative to the set of types of acceptable complexity.Type parameter inference for constructor patterns..Assume a constructor pat-tern C (p1, ..., pn) where class C has type type parameters a1, ..., an. These type pa- rameters are inferred in the same way as for the typed pattern (: C [a1, ..., an]) .Example 8.3.1 Consider the program fragment:val x: Anyx match {case y: List[a] => ... }Here, the type pattern List[a] is matched against the expected type Any. The pat-tern binds the type variable a. Since List[a] conforms to Any for every type argu-ment, there are no constraints on a. Hence, a is introduced as an abstract type with no bounds. The scope of a is right-hand side of its case clause.On the other hand, if x is declared asval x: List[List[String]],this generates the constraint List[a] <: List[List[String]], which simplifies to a <: List[String], because List is covariant. Hence, a is introduced with upperbound List[String].Example 8.3.2 Consider the program fragment:val x: Anyx match { case y: List[String] => ...}Scala does not maintain information about type arguments at run-time, so there isno way to check that x is a list of strings. Instead, the Scala compiler will erase (§3.7) the pattern to List[]; that is, it will only test whether the top-level runtime-classof the value x conforms to List, and the pattern match will succeed if it does. Thismight lead to a class cast exception later on, in the case where the list x contains elements other than strings. The Scala compiler will flag this potential loss of type-safety with an "unchecked" warning message.Example 8.3.3 Consider the program fragmentclass Term[A] -------------------------------------------------------------------------------122Pattern Matchingclass Number(val n: Int) extends Term[Int]def f[B](t: Term[B]) : B = t match { case y: Number => y.n}The expected type of the pattern y: Number is Term[B]. The type Number does notconform to Term[B]; hence Case 2 of the rules above applies. This means that b is treated as another type variable for which subtype constraints are inferred. Inour case the applicable constraint is Number <: Term[B], which entails B = Int.Hence, B is treated in the case clause as an abstract type with lower and upper bound Int. Therefore, the right hand side of the case clause, y.n, of type Int, is found toconform to the function's declared result type, Number.8.4Pattern Matching Expressions Syntax:Expr::=PostfixExpr `match' `{' CaseClauses `}'CaseClauses::=CaseClause {CaseClause}CaseClause::=`case' Pattern [Guard] `=>' Block A pattern matching expressione match { case p1 => b1 . . . case pn => bn }consists of a selector expression e and a number n > 0 of cases. Each case consistsof a (possibly guarded) pattern pi and a block bi . Each pi might be complemented by a guard if e where e is a boolean expression. The scope of the pattern variablesin pi comprises the pattern's guard and the corresponding block bi .Let T be the type of the selector expression e and let a1, ..., am be the type param- eters of all methods enclosing the pattern matching expression. For every ai , let Libe its lower bound and Ui be its higher bound. Every pattern p {p1,, ..., pn} canbe typed in two ways. First, it is attempted to type p with T as its expected type. If this fails, p is instead typed with a modified expected type T which results from Tby replacing every occurrence of a type parameter ai by undefined. If this secondstep fails also, a compile-time error results. If the second step succeeds, let Tp be the type of pattern p seen as an expression. One then determines minimal boundsL , . . . , L, . . . , Uand U1m and maximal bounds U1m such that for all i , Li <: Li i <: Uiand the following constraint system is satisfied:L1 <: a1 <: U1  ... Lm <: am <: Um  Tp <: TIf no such bounds can be found, a compile time error results. If such bounds are found, the pattern matching clause starting with p is then typed under the assump--------------------------------------------------------------------------------8.4 Pattern Matching Expressions 123tion that each ai has lower bound L instead of Linsteadii and has upper bound Uiof Ui .The expected type of every block bi is the expected type of the whole pattern match- ing expression. The type of the pattern matching expression is then the weak leastupper bound (§3.5.3) of the types of all blocks bi .When applying a pattern matching expression to a selector value, patterns are tried in sequence until one is found which matches the selector value (§8.1) .Say this caseis case pi  bi . The result of the whole expression is then the result of evaluating bi ,where all pattern variables of pi are bound to the corresponding parts of the selector value. If no matching pattern is found, a scala.MatchError exception is thrown.The pattern in a case may also be followed by a guard suffix if e with a booleanexpression e. The guard expression is evaluated if the preceding pattern in the case matches. If the guard expression evaluates to true, the pattern match succeeds asnormal. If the guard expression evaluates to false, the pattern in the case is con-sidered not to match and the search for a matching pattern continues. In the interest of efficiency the evaluation of a pattern matching expression may trypatterns in some other order than textual sequence. This might affect evaluationthrough side effects in guards. However, it is guaranteed that a guard expression is evaluated only if the pattern it guards matches.If the selector of a pattern match is an instance of a sealed class (§5.2) ,the com-pilation of pattern matching can emit warnings which diagnose that a given set of patterns is not exhaustive, i.e. that there is a possibility of a MatchError being raisedat run-time.Example 8.4.1 Consider the following definitions of arithmetic terms:abstract class Term[T] case class Lit(x: Int) extends Term[Int]case class Succ(t: Term[Int]) extends Term[Int]case class IsZero(t: Term[Int]) extends Term[Boolean]case class If[T](c: Term[Boolean], t1: Term[T],t2: Term[T]) extends Term[T]There are terms to represent numeric literals, incrementation, a zero test, and aconditional. Every term carries as a type parameter the type of the expression it representes (either Int or Boolean) .A type-safe evaluator for such terms can be written as follows.def eval[T](t: Term[T]) : T = t match {case Lit(n)=> ncase Succ(u) => eval(u) + 1case IsZero(u)=> eval(u) == 0case If(c, u1, u2) => eval(if (eval(c) ) u1 else u2)------------------------------------------------------------------------------- 124Pattern Matching}Note that the evaluator makes crucial use of the fact that type parameters of enclos-ing methods can acquire new bounds through pattern matching. For instance, the type of the pattern in the second case, Succ(u) , is Int. It conformsto the selector type T only if we assume an upper and lower bound of Int for T.Under the assumption Int <: T <: Int we can also verify that the type right hand side of the second case, Int conforms to its expected type, T.8.5Pattern Matching Anonymous FunctionsSyntax:BlockExpr ::= `{' CaseClauses `}'An anonymous function can be defined by a sequence of cases { case p1 => b1 . . . case pn => bn }whichappearasanexpressionwithoutapriormatch.Theex- pectedtypeofsuchanexpressionmustinpartbedefined.Itmust be eitherscala.Functionk[S1, . . . , Sk, R] for some k > 0, orscala.PartialFunction[S1, R], where the argument type(s) S1, . . . , Sk mustbe fully determined, but the result type R may be undetermined.If the expected type is scala.Functionk[S1, ..., Sk, R] , the expression is taken to be equivalent to the anonymous function:(x1 : S1, . . . , xk : Sk) => (x1, . . . , xk) match {case p1 => b1 . . . case pn => bn}Here, each xi is a fresh name. As was shown in (§6.23) ,this anonymous function is in turn equivalent to the following instance creation expression, where T is theweak least upper bound of the types of all bi .new scala.Functionk[S1, . . . , Sk, T ] {def apply(x1 : S1, . . . , xk : Sk) : T = (x1, . . . , xk) match { case p1 => b1 . . . case pn => bn}}If the expected type is scala.PartialFunction[S, R], the expression is taken tobe equivalent to the following instance creation expression: new scala.PartialFunction[S, T ] {-------------------------------------------------------------------------------8.5 Pattern Matching Anonymous Functions125def apply(x: S) : T = x match { case p1 => b1 . . . case pn => bn}def isDefinedAt(x: S) : Boolean = {case p1 => true . . . case pn => truecase _ => false}}Here, x is a fresh name and T is the weak least upper bound of the types of all bi . The final default case in the isDefinedAt method is omitted if one of the patternsp1, ..., pn is already a variable or wildcard pattern.Example 8.5.1 Here is a method which uses a fold-left operation /: to compute the scalar product of two vectors:def scalarProduct(xs: Array[Double], ys: Array[Double]) =(0.0 /: (xs zip ys) ) {case (a, (b, c) ) => a + b * c}The case clauses in this code are equivalent to the following anonymous funciton: (x, y) => (x, y) match {case (a, (b, c) ) => a + b * c}-------------------------------------------------------------------------------------------------------------------------------------------------------------- Chapter 9Top-Level Definitions9.1Compilation UnitsSyntax:CompilationUnit::={`package' QualId semi} TopStatSeqTopStatSeq ::=TopStat {semi TopStat}TopStat::={Annotation} {Modifier} TmplDef|Import|Packaging|PackageObject |QualId::=id {`.' id}A compilation unit consists of a sequence of packagings, import clauses, and classand object definitions, which may be preceded by a package clause. A compilation unitpackage p1;. . .package pn;statsstarting with one or more package clauses is equivalent to a compilation unit con-sisting of the packaging package p1 { . . .package pn {stats} . . .}-------------------------------------------------------------------------------128Top-Level Definitions Implicitly imported into every compilation unit are, in that order : the packagejava.lang, the package scala, and the object scala.Predef (§12.5) .Members ofa later import in that order hide members of an earlier import. 9.2PackagingsSyntax:Packaging::=`package' QualId [nl] `{' TopStatSeq `}'A package is a special object which defines a set of member classes, objects and packages. Unlike other objects, packages are not introduced by a definition. In-stead, the set of members of a package is determined by packagings.A packaging package p { ds } injects all definitions in ds as members into the package whose qualified name is p. Members of a package are called top-level def-initions. If a definition in ds is labeled private, it is visible only for other membersin the package. Inside the packaging, all members of package p are visible under their simplenames. However this rule does not extend to members of enclosing packages ofp that are designated by a prefix of the path p. Example 9.2.1 Given the packagingpackage org.net.prj {...}all members of package org.net.prj are visible under their simple names, butmembers of packages org or org.net require explicit qualification or imports. Selections p.m from p as well as imports from p work as for objects. However, unlikeother objects, packages may not be used as values. It is illegal to have a package withthe same fully qualified name as a module or a class. Top-level definitions outside a packaging are assumed to be injected into a specialempty package. That package cannot be named and therefore cannot be imported.However, members of the empty package are visible to each other without qualifi- cation.9.3Package ObjectsSyntax:PackageObject::=`package' `object' ObjectDef------------------------------------------------------------------------------- 9.4 Package References129A package object package object p extends t adds the members of template tto the package p. There can be only one package object per package. The standard naming convention is to place the definition above in a file named package.scalathat's located in the directory corresponding to package p.The package object should not define a member with the same name as one of the top-level objects or classes defined in package p. If there is a name conflict, thebehavior of the program is currently undefined. It is expected that this restrictionwill be lifted in a future version of Scala. 9.4Package ReferencesSyntax:QualId::=id {`.' id}A reference to a package takes the form of a qualified identifier. Like all other ref-erences, package references are relative. That is, a package reference starting in a name p will be looked up in the closest enclosing scope that defines a membernamed p.The special predefined name root_ refers to the outermost root package whichcontains all top-level packages. Example 9.4.1 Consider the following program:package b {class B}package a.b {class A {val x = new root.b.B}}Here, the reference root.b.B refers to class B in the toplevel package b. If the root_ prefix had been omitted, the name b would instead resolve to the packagea.b, and, provided that package does not also contain a class B, a compiler-timeerror would result.9.5 ProgramsA program is a top-level object that has a member method main of type(Array[String]) Unit. Programs can be executed from a command shell. The pro-------------------------------------------------------------------------------- 130Top-Level Definitionsgram's command arguments are are passed to the main method as a parameter oftype Array[String].The main method of a program can be directly defined in the object, or it can be inherited. The scala library defines a class scala.App that defines an empty inher-ited main method. An objects m inheriting from this class is thus a program, whichexecutes the initializaton code of the object m. Example 9.5.1 The following example will create a hello world program by defininga method main in module test.HelloWorld.package testobject HelloWord {def main(args: Array[String]) { println("hello world") } }This program can be started by the commandscala test.HelloWorldIn a Java environment, the commandjava test.HelloWorldwould work as well.HelloWorld can also be defined without a main method by inheriting from App in- stead:package testobject HelloWord extends App {println("hello world")}------------------------------------------------------------------------------- Chapter 10XML expressions and patternsBy Burak EmirThis chapter describes the syntactic structure of XML expressions and patterns. Itfollows as closely as possible the XML 1.0 specification [W3C],changes being man- dated by the possibility of embedding Scala code fragments.10.1XML expressionsXML expressions are expressions generated by the following production, where theopening bracket `<' of the first element must be in a position to start the lexical XML mode (§1.5) .Syntax:XmlExpr ::= XmlContent {Element}Well-formedness constraints of the XML specification apply, which means for in-stance that start tags and end tags must match, and attributes may only be defined once, with the exception of constraints related to entity resolution.The following productions describe Scala's extensible markup language, designedas close as possible to the W3C extensible markup language standard. Only the pro- ductions for attribute values and character data are changed. Scala does not sup-port declarations, CDATA sections or processing instructions. Entity references arenot resolved at runtime. Syntax:Element::=EmptyElemTag|STag Content ETag-------------------------------------------------------------------------------132 XML expressions and patternsEmptyElemTag::=`<' Name {S Attribute} [S] `/>'STag::=`<' Name {S Attribute} [S] `>'ETag ::=`</' Name [S] '>'Content::=[CharData] {Content1 [CharData]}Content1::=XmlContent|Reference |ScalaExprXmlContent::=Element|CDSect|PI|CommentIf an XML expression is a single element, its value is a runtime representation of an XML node (an instance of a subclass of scala.xml.Node) . If the XML expressionconsists of more than one element, then its value is a runtime representation of asequence of XML nodes (an instance of a subclass of scala.Seq[scala.xml.Node]) . If an XML expression is an entity reference, CDATA section, processing instructionsor a comments, it is represented by an instance of the corresponding Scala runtimeclass.By default, beginning and trailing whitespace in element content is removed, and consecutive occurrences of whitespace are replaced by a single space character\u0020. This behavior can be changed to preserve all whitespace with a compileroption.Syntax:Attribute ::=Name Eq AttValueAttValue::=`"' {CharQ | CharRef} `"'|`'' {CharA | CharRef} `''|ScalaExpr ScalaExpr::=BlockCharData::={ CharNoRef } without {CharNoRef}`{'CharB {CharNoRef}and without {CharNoRef}`]]>'{CharNoRef}XML expressions may contain Scala expressions as attribute values or within nodes. In the latter case, these are embedded using a single opening brace `{' and ended bya closing brace `}'. To express a single opening braces within XML text as generatedby CharData, it must be doubled. Thus, `{{' represents the XML text `{' and does not introduce an embedded Scala expression.Syntax:-------------------------------------------------------------------------------10.2 XML patterns133BaseChar, Char, Comment, CombiningChar, Ideographic, NameChar, S, Reference ::="as in W3C XML"Char1::=Char without `<' | `&'CharQ::=Char1 without `"'CharA::= Char1 without `''CharB::=Char1 without '{'Name::=XNameStart {NameChar}XNameStart::= `' | BaseChar | Ideographic (as in W3C XML, but without `:'10.2XML patternsXML patterns are patterns generated by the following production, where the open-ing bracket `<' of the element patterns must be in a position to start the lexical XML mode (§1.5) .Syntax:XmlPattern::= ElementPatternWell-formedness constraints of the XML specification apply.An XML pattern has to be a single element pattern. It matches exactly those runtime representations of an XML tree that have the same structure as described by thepattern. XML patterns may contain Scala patterns(§8.4) .Whitespace is treated the same way as in XML expressions. Patterns that are entity references, CDATA sections, processing instructions and comments match runtimerepresentations which are the the same.By default, beginning and trailing whitespace in element content is removed, and consecutive occurrences of whitespace are replaced by a single space character\u0020. This behavior can be changed to preserve all whitespace with a compileroption.Syntax:ElemPattern ::=EmptyElemTagP|STagP ContentP ETagPEmptyElemTagP ::=`<' Name [S] `/>'STagP::=`<' Name [S] `>' ETagP::=`</' Name [S]`>'ContentP::=[CharData] {(ElemPattern|ScalaPatterns) [CharData]}------------------------------------------------------------------------------- 134XML expressions and patternsContentP1::=ElemPattern|Reference|CDSect|PI|Comment |ScalaPatternsScalaPatterns ::=`{' Patterns `}'-------------------------------------------------------------------------------Chapter 11User-Defined Annotations Syntax:Annotation::=`@' SimpleType {ArgumentExprs}ConstrAnnotation ::=`@' SimpleType ArgumentExprsUser-defined annotations associate meta-information with definitions. A simple annotation has the form @c or @c(a1, ..., an) . Here, c is a constructor of a class C ,which must conform to the class scala.Annotation.Annotations may apply to definitions or declarations, types, or expressions. An an- notation of a definition or declaration appears in front of that definition. An anno-tation of a type appears after that type. An annotation of an expression e appearsafter the expression e, separated by a colon. More than one annotation clause may apply to an entity. The order in which these annotations are given does not matter.Examples:@serializable class C { ... }// A class annotation.@transient @volatile var m: Int // A variable annotationString @local// A type annotation(e: @unchecked) match { ... }// An expression annotationThe meaning of annotation clauses is implementation-dependent. On the Java plat- form, the following annotations have a standard meaning.@transientMarks a field to be non-persistent; this is equivalent to the transientmodifier in Java.@volatile -------------------------------------------------------------------------------136User-Defined AnnotationsMarks a field which can change its value outside the control of the pro- gram; this is equivalent to the volatile modifier in Java.@serializableMarks a class to be serializable; this is equivalent to inheriting from thejava.io.Serializable interface in Java. @SerialVersionUID(<longlit>)Attaches a serial version identifier (a long constant) to a class. This isequivalent to a the following field definition in Java:private final static SerialVersionUID = <longlit> @throws(<classlit>)A Java compiler checks that a program contains handlers for checkedexceptions by analyzing which checked exceptions can result from exe-cution of a method or constructor. For each checked exception which is a possible result, the throws clause for the method or constructor mustmention the class of that exception or one of the superclasses of theclass of that exception.@deprecated(<stringlit>) Marks a definition as deprecated. Accesses to the defined entity willthen cause a deprecated warning mentioning the message <stringlit>to be issued from the compiler. Deprecated warnings are suppressed in code that belongs itself to a definition that is labeled deprecated [dot] [at] scala [dot] reflect [dot] BeanPropertyWhen prefixed to a definition of some variable X, this annotation causesgetter and setter methods getX, setX in the Java bean style to be added in the class containing the variable. The first letter of the variable ap-pears capitalized after the get or set. When the annotation is added tothe definition of an immutable value definition X, only a getter is gen- erated. The construction of these methods is part of code-generation;therefore, these methods become visible only once a classfile for thecontaining class is generated [dot] [at] scala [dot] reflect [dot] BooleanBeanProperty -------------------------------------------------------------------------------137This annotation is equivalent to scala.reflect.BeanProperty, but thegenerated getter method is named isX instead of getX. @uncheckedWhen applied to the selector of a match expression, this attribute sup-presses any warnings about non-exhaustive pattern matches whichwould otherwise be emitted. For instance, no warnings would be pro- duced for the method definition below.def f(x: Option[Int]) = (x: @unchecked) match {case Some(y) => y}Without the @unchecked annotation, a Scala compiler could infer that the pattern match is non-exhaustive, and could produce a warning be-cause Option is a sealed class.@uncheckedStableWhen applied a value declaration or definition, it allows the defined value to appear in a path, even if its type is volatile (§??) . For instance,the following member definitions are legal:type A { type T }type B@uncheckedStable val x: A with B // volatile type val y: x.T// OK since `x' is still a pathWithout the @uncheckedStable annotation, the designator x would notbe a path since its type A with B is volatile. Hence, the reference x.T would be malformed.When applied to value declarations or definitions that have non-volatiletypes, the annotation has no effect.@specializedWhen applied to the definition of a type parameter, this annotation causes the compiler to generate specialized definitions for primitivetypes. An optional list of primitive types may be given, in which casespecialization takes into account only those types. For instance, the fol- lowing code would generate specialized traits for Unit, Int and Doubletrait Function0[@specialized(Unit, Int, Double) T] {def apply: T}------------------------------------------------------------------------------- 138User-Defined AnnotationsWhenever the static type of an expression matches a specialized variantof a definition, the compiler will instead use the specialized version. See [Dra10]for more details of the implementation.Other annotations may be interpreted by platform- or application-dependent tools.Class scala.Annotation has two sub-traits which are used to indicate how these annotations are retained. Instances of an annotation class inheriting from traitscala.ClassfileAnnotation will be stored in the generated class files. Instancesof an annotation class inheriting from trait scala.StaticAnnotation will be visible to the Scala type-checker in every compilation unit where the annotated symbol isaccessed. An annotation class can inherit from both scala.ClassfileAnnotationand scala.StaticAnnotation. If an annotation class inherits from neitherscala.ClassfileAnnotation nor scala.StaticAnnotation, its instances are visibleonly locally during the compilation run that analyzes them.Classes inheriting from scala.ClassfileAnnotation may be subject to further re- strictions in order to assure that they can be mapped to the host environment. Inparticular, on both the Java and the .NET platforms, such classes must be toplevel;i.e. they may not be contained in another class or object. Additionally, on both Java and .NET, all constructor arguments must be constant expressions.-------------------------------------------------------------------------------Chapter 12The Scala Standard Library The Scala standard library consists of the package scala with a number of classesand modules. Some of these classes are described in the following.12.1Root ClassesFigure 12.1illustrates Scala's class hierarchy. The root of this hierarchy is formed by class Any. Every class in a Scala execution environment inherits directly or indirectlyfrom this class. Class Any has two direct subclasses: AnyRef and AnyVal.The subclass AnyRef represents all values which are represented as objects in the underlying host system. Every user-defined Scala class inherits directly or indi-rectly from this class. Furthermore, every user-defined Scala class also inheritsthe trait scala.ScalaObject. Classes written in other languages still inherit from scala.AnyRef, but not from scala.ScalaObject.The class AnyVal has a fixed number of subclasses, which describe values which arenot implemented as objects in the underlying host system. Classes AnyRef and AnyVal are required to provide only the members declared inclass Any, but implementations may add host-specific methods to these classes (forinstance, an implementation may identify class AnyRef with its own root class for objects) .The signatures of these root classes are described by the following definitions.package scala/** The universal root class */abstract class Any {/** Defined equality; abstract here */ def equals(that: Any) : Boolean-------------------------------------------------------------------------------140The Scala Standard LibraryO(j aa.l a.bjet)ngcvFigure 12.1: Class hierarchy of Scala./** Semantic equality between values */ final def == (that: Any) : Boolean=if (null eq this) null eq that else this equals that/** Semantic inequality between values */final def != (that: Any) : Boolean =!(this == that)/** Hash code; abstract here */def hashCode: Int = . . ./** Textual representation; abstract here */def toString: String = . . ./** Type test; needs to be inlined to work as given */ def isInstanceOf[a]: Boolean/** Type cast; needs to be inlined to work as given */ */def asInstanceOf[A]: A = this match {case x: A => xcase _ => if (this eq null) this else throw new ClassCastException()}}-------------------------------------------------------------------------------12.2 Value Classes141/** The root class of all value types */ final class AnyVal extends Any/** The root class of all reference types */class AnyRef extends Any {def equals(that: Any) : Boolean= this eq thatfinal def eq(that: AnyRef) : Boolean = . . . // reference equality final def ne(that: AnyRef) : Boolean = !(this eq that)def hashCode: Int = . . .// hashCode computed from allocation addressdef toString: String= . . . // toString computed from hashCode and class name def synchronized[T](body: => T) : T // execute `body` in while locking `this`.}/** A mixin class for every user-defined Scala class */trait ScalaObject extends AnyRefThe type test x.isInstanceOf[T ] is equivalent to a typed pattern match x match {case : T=> truecase _ => false}where the type T is the same as T except if T is of the form D or D[tps] whereD is a type member of some outer class C . In this case T is C #D (or C #D[t ps], respectively) , whereas T itself would expand to C .this.D[t p s]. In other words, anisInstanceOf test does not check for theThe test x.asInstanceOf[T ] is treated specially if T is a numeric value type (§12.2) .In this case the cast will be translated to an application of a conversionmethod x.toT (§12.2.1) .For non-numeric values x the operation will raise aClassCastException.12.2 Value ClassesValue classes are classes whose instances are not represented as objects by the un-derlying host system. All value classes inherit from class AnyVal. Scala implemen-tations need to provide the value classes Unit, Boolean, Double, Float, Long, Int, Char, Short, and Byte (but are free to provide others as well) . The signatures ofthese classes are defined in the following.------------------------------------------------------------------------------- 142The Scala Standard Library12.2.1 Numeric Value TypesClasses Double, Float, Long, Int, Char, Short, and Byte are together called numericvalue types. Classes Byte, Short, or Char are called subrange types. Subrange types, as well as Int and Long are called integer types, whereas Float and Double are calledfloating point types.Numeric value types are ranked in the following partial order:Byte - Short \Int - Long - Float - Double/CharByte and Short are the lowest-ranked types in this order, whereas Double is thehighest-ranked. Ranking does not imply a conformance (§3.5.2) relationship; for instance Int is not a subtype of Long. However, object Predef (§12.5) defines views(§7.3) from every numeric value type to all higher-ranked numeric value types.Therefore, lower-ranked types are implicitly converted to higher-ranked types when required by the context (§6.26) .Given two numeric value types S and T , the operation type of S and T is defined asfollows: If both S and T are subrange types then the operation type of S and T is Int. Otherwise the operation type of S and T is the larger of the two types wrt ranking.Given two numeric values v and w the operation type of v and w is the operationtype of their run-time types. Any numeric value type T supports the following methods.· Comparison methods for equals (==) , not-equals (!=) , less-than (<) , greater-than (>) , less-than-or-equals (<=) , greater-than-or-equals (>=) , which each ex- ist in 7 overloaded alternatives. Each alternative takes a parameter of somenumeric value type. Its result type is type Boolean. The operation is evalu-ated by converting the receiver and its argument to their operation type and performing the given comparison operation of that type.· Arithmetic methods addition (+) , subtraction (-) , multiplication (*) , division(/) , and remainder (%) , which each exist in 7 overloaded alternatives. Each alternative takes a parameter of some numeric value type U . Its result type isthe operation type of T and U . The operation is evaluated by converting thereceiver and its argument to their operation type and performing the given arithmetic operation of that type.· Parameterless arithmethic methods identity (+) and negation (-) , with resulttype T . The first of these returns the receiver unchanged, whereas the second returns its negation.· Conversion methods toByte, toShort, toChar, toInt, toLong, toFloat,-------------------------------------------------------------------------------12.2 Value Classes 143toDouble which convert the receiver object to the target type, using the rulesof Java's numeric type cast operation. The conversion might truncate the nu-meric value (as when going from Long to Int or from Int to Byte) or it might lose precision (as when going from Double to Float or when converting be-tween Long and Float) .Integer numeric value types support in addition the following operations:· Bit manipulation methods bitwise-and (&) , bitwise-or |, and bitwise- exclusive-or (^) , which each exist in 5 overloaded alternatives. Each alterna-tive takes a parameter of some integer numeric value type. Its result type isthe operation type of T and U . The operation is evaluated by converting the receiver and its argument to their operation type and performing the givenbitwise operation of that type.· A parameterless bit-negation method (~) . Its result type is the reciver type T or Int, whichever is larger. The operation is evaluated by converting the receiverto the result type and negating every bit in its value.· Bit-shift methods left-shift (<<) , arithmetic right-shift (>>) , and unsigned right-shift (>>>) . Each of these methods has two overloaded alternatives,which take a parameter n of type Int, respectively Long. The result type ofthe operation is the receiver type T , or Int, whichever is larger. The operation is evaluated by converting the receiver to the result type and performing thespecified shift by n bits.Numeric value types also implement operations equals, hashCode, and toStringfrom class Any. The equals method tests whether the argument is a numeric value type. If this istrue, it will perform the == operation which is appropriate for that type. That is, theequals method of a numeric value type can be thought of being defined as follows: def equals(other: Any) : Boolean = other match {case that: Byte=> this == thatcase that: Short=> this == thatcase that: Char=> this == that case that: Int=> this == thatcase that: Long=> this == thatcase that: Float=> this == thatcase that: Double => this == thatcase _ => false }The hashCode method returns an integer hashcode that maps equal numeric val-ues to equal results. It is guaranteed to be the identity for for type Int and for allsubrange types. -------------------------------------------------------------------------------144The Scala Standard LibraryThe toString method displays its receiver as an integer or floating point number. Example 12.2.1 As an example, here is the signature of the numeric value type Int:package scalaabstract sealed class Int extends AnyVal {def == (that: Double) : Boolean// double equality def == (that: Float) : Boolean// float equalitydef == (that: Long) : Boolean// long equalitydef == (that: Int) : Boolean// int equalitydef == (that: Short) : Boolean // int equalitydef == (that: Byte) : Boolean// int equalitydef == (that: Char) : Boolean// int equality/* analogous for !=, <, >, <=, >= */ def + (that: Double) : Double// double additiondef + (that: Float) : Double// float additiondef + (that: Long) : Long// long additiondef + (that: Int) : Int // int additiondef + (that: Short) : Int// int additiondef + (that: Byte) : Int// int additiondef + (that: Char) : Int// int addition/* analogous for -, *, /, % */ def & (that: Long) : Long// long bitwise anddef & (that: Int) : Int// int bitwise anddef & (that: Short) : Int// int bitwise anddef & (that: Byte) : Int // int bitwise anddef & (that: Char) : Int// int bitwise and/* analogous for |, ^ */def << (cnt: Int) : Int// int left shiftdef << (cnt: Long) : Int // long left shift/* analogous for >>, >>> */def unary+ : Int// int identitydef unary- : Int// int negationdef unary~ : Int// int bitwise negation def toByte: Byte// convert to Bytedef toShort: Short// convert to Shortdef toChar: Char// convert to Chardef toInt: Int// convert to Int def toLong: Long// convert to Longdef toFloat: Float// convert to Floatdef toDouble: Double// convert to Double}------------------------------------------------------------------------------- 12.3 Standard Reference Classes14512.2.2 Class BooleanClass Boolean has only two values: true and false. It implements operations asgiven in the following class definition. package scalaabstract sealed class Boolean extends AnyVal {def && (p: => Boolean) : Boolean = // boolean andif (this) p else falsedef || (p: => Boolean) : Boolean = // boolean or if (this) true else pdef &(x: Boolean) : Boolean =// boolean strict andif (this) x else falsedef |(x: Boolean) : Boolean =// boolean strict or if (this) true else xdef == (x: Boolean) : Boolean =// boolean equalityif (this) x else x.unary!def != (x: Boolean) : Boolean// boolean inequalityif (this) x.unary! else x def unary!: Boolean// boolean negationif (this) false else true}The class also implements operations equals, hashCode, and toString from classAny.The equals method returns true if the argument is the same boolean value as the receiver, false otherwise. The hashCode method returns a fixed, implementation-specific hash-code when invoked on true, and a different, fixed, implementation-specific hash-code when invoked on false. The toString method returns the re- ceiver converted to a string, i.e. either "true" or "false".12.2.3 Class UnitClass Unit has only one value: () . It implements only the three methods equals,hashCode, and toString from class Any. The equals method returns true if the argument is the unit value () , false oth-erwise. The hashCode method returns a fixed, implementation-specific hash-code,The toString method returns "() ". 12.3Standard Reference ClassesThis section presents some standard Scala reference classes which are treated in aspecial way in Scala compiler ­ either Scala provides syntactic sugar for them, or the Scala compiler generates special code for their operations. Other classes in the-------------------------------------------------------------------------------146The Scala Standard Library standard Scala library are documented in the Scala library documentation by HTMLpages.12.3.1 Class StringScala's String class is usually derived from the standard String class of the underly- ing host system (and may be identified with it) . For Scala clients the class is takento support in each case a methoddef + (that: Any) : Stringwhich concatenates its left operand with the textual representation of its right operand.12.3.2 The Tuple classesScala defines tuple classes Tuplen for n = 2, ..., 9. These are defined as follows.package scalacase class Tuplen[+a1, ..., +an](1: a1, ..., n: an) { def toString = "(" ++ 1 ++ "," ++ . . . ++ "," ++ n ++ ") "}The implicitly imported Predef object (§12.5) defines the names Pair as an alias of Tuple2 and Triple as an alias for Tuple3.12.3.3 The Function ClassesScala defines function classes Functionn for n = 1, ..., 9. These are defined as fol-lows.package scala trait Functionn[-a1, ..., -an, +b] {def apply(x1: a1, ..., xn: an) : bdef toString = "<function>"}A subclass of Function1 represents partial functions, which are undefined on some points in their domain. In addition to the apply method of functions, partial func-tions also have a isDefined method, which tells whether the function is defined atthe given argument: class PartialFunction[-A, +B] extends Function1[A, B] {def isDefinedAt(x: A) : Boolean}-------------------------------------------------------------------------------12.3 Standard Reference Classes 147The implicitly imported Predef object (§12.5) defines the name Function as an aliasof Function1.12.3.4 Class ArrayThe class of generic arrays is given as follows. final class Array[A](len: Int) extends Seq[A] {def length: Int = lendef apply(i: Int) : A = . . .def update(i: Int, x: A) : Unit = . . .def elements: Iterator[A] = . . . def subArray(from: Int, end: Int) : Array[A] = . . .def filter(p: A => Boolean) : Array[A] = . . .def map[B](f: A => B) : Array[B] = . . .def flatMap[B](f: A => Array[B]) : Array[B] = . . . }If T is not a type parameter or abstract type, the type Array[T ] is represented as thenative array type []T in the underlying host system. In that case length returns thelength of the array, apply means subscripting, and update means element update. Because of the syntactic sugar for apply and update operations (§6.26,we have thefollowing correspondences between Scala and Java/C# code for operations on anarray xs:Scala Java/C#xs.lengthxs.lengthxs(i)xs[i]xs(i) = exs[i] = eArrays also implement the sequence trait scala.Seq by defining an elementsmethod which returns all elements of the array in an Iterator. Because of the tension between parametrized types in Scala and the ad-hoc imple-mentation of arrays in the host-languages, some subtle points need to be taken intoaccount when dealing with arrays. These are explained in the following. First, unlike arrays in Java or C#, arrays in Scala are not co-variant; That is, S <: Tdoes not imply Array[S] <: Array[T ] in Scala. However, it is possible to cast anarray of S to an array of T if such a cast is permitted in the host environment. For instance Array[String] does not conform to Array[Object], even thoughString conforms to Object. However, it is possible to cast an expression of typeArray[String] to Array[Object], and this cast will succeed without raising a ClassCastException. Example:val xs = new Array[String](2)// val ys: Array[Object] = xs// **** error: incompatible types------------------------------------------------------------------------------- 148The Scala Standard Libraryval ys: Array[Object] = xs.asInstanceOf[Array[Object]] // OKSecond, for polymorphic arrays, that have a type parameter or abstract type T astheir element type, a representation different from []T might be used. However, it is guaranteed that isInstanceOf and asInstanceOf still work as if the array used thestandard representation of monomorphic arrays:val ss = new Array[String](2)def f[T](xs: Array[T]) : Array[String] = if (xs.isInstanceOf[Array[String]]) xs.asInstanceOf[Array[String])else throw new Error("not an instance")f(ss)// returns ssThe representation chosen for polymorphic arrays also guarantees that polymor- phic array creations work as expected. An example is the following implementationof method mkArray, which creates an array of an arbitrary type T , given a sequenceof T 's which defines its elements. def mkArray[T](elems: Seq[T]) : Array[T] = {val result = new Array[T](elems.length)var i = 0for (elem <- elems) {result(i) = elemi += 1} }Note that under Java's erasure model of arrays the method above would not work asexpected ­ in fact it would always return an array of Object.Third, in a Java environment there is a method System.arraycopy which takes two objects as parameters together with start indices and a length argument, and copieselements from one object to the other, provided the objects are arrays of compatibleelement types. System.arraycopy will not work for Scala's polymorphic arrays be- cause of their different representation. One should instead use method Array.copywhich is defined in the companion object of class Array. This companion objectalso defines various constructor methods for arrays, as well as the extractor method unapplySeq (§8.1.8) which enables pattern matching over arrays.package scalaobject Array {/** copies array elements from `src' to `dest'. */def copy(src: AnyRef, srcPos: Int, dest: AnyRef, destPos: Int, length: Int) : Unit = . . .-------------------------------------------------------------------------------12.4 Class Node149/** Concatenate all argument arrays into a single array. */ def concat[T](xs: Array[T]*) : Array[T] = . . ./** Create a an array of successive integers. */def range(start: Int, end: Int) : Array[Int] = . . ./** Create an array with given elements. */ def apply[A <: AnyRef](xs: A*) : Array[A] = . . ./** Analogous to above. */def apply(xs: Boolean*) : Array[Boolean] = . . .def apply(xs: Byte*): Array[Byte]= . . . def apply(xs: Short*) : Array[Short]= . . .def apply(xs: Char*): Array[Char]= . . .def apply(xs: Int*): Array[Int]= . . .def apply(xs: Long*) : Array[Long]= . . .def apply(xs: Float*) : Array[Float]= . . .def apply(xs: Double*) : Array[Double] = . . .def apply(xs: Unit*): Array[Unit] = . . ./** Create an array containing several copies of an element. */def make[A](n: Int, elem: A) : Array[A] = {/** Enables pattern matching over arrays */def unapplySeq[A](x: Array[A]) : Option[Seq[A]] = Some(x) }Example 12.3.1 The following method duplicates a given argument array and re-turns a pair consisting of the original and the duplicate:def duplicate[T](xs: Array[T]) = {val ys = new Array[T](xs.length) Array.copy(xs, 0, ys, 0, xs.length)(xs, ys)}12.4Class Nodepackage scala.xmltrait Node {/** the label of this node */def label: String -------------------------------------------------------------------------------150The Scala Standard Library/** attribute axis */def attribute: Map[String, String] /** child axis (all children of this node) */def child: Seq[Node]/** descendant axis (all descendants of this node) */def descendant: Seq[Node] = child.toList.flatMap {x => x::x.descendant.asInstanceOf[List[Node]] }/** descendant axis (all descendants of this node) */def descendantorself: Seq[Node] = this::child.toList.flatMap {x => x::x.descendant.asInstanceOf[List[Node]]} override def equals(x: Any) : Boolean = x match {case that:Node =>that.label == this.label &&that.attribute.sameElements(this.attribute) &&that.child.sameElements(this.child) case _ => false}/** XPath style projection function. Returns all children of this node*that are labeled with 'that'. The document order is preserved.*/ def \(that: Symbol) : NodeSeq = {new NodeSeq({that.name match {case "" => child.toListcase _ =>var res:List[Node] = Nil for (x <- child.elements if x.label == that.name) {res = x::res}res.reverse}})}/** XPath style projection function. Returns all nodes labeled with the *name 'that' from the 'descendantorself' axis. Document order is preserved.*/def \\(that: Symbol) : NodeSeq = {------------------------------------------------------------------------------- 12.4 Class Node151new NodeSeq(that.name match {case "" => this.descendantorselfcase _ => this.descendantorself.asInstanceOf[List[Node]]. filter(x => x.label == that.name)})}/** hashcode for this XML node */override def hashCode =Utility.hashCode(label, attribute.toList.hashCode, child) /** string representation of this node */override def toString = Utility.toXML(this)}-------------------------------------------------------------------------------152 The Scala Standard Library12.5The Predef ObjectThe Predef object defines standard functions and type aliases for Scala programs.It is always implicitly imported, so that all its defined members are available with- out qualification. Its definition for the JVM environment conforms to the followingsignature:package scalaobject Predef {// classOf --------------------------------------------------------- /** Returns the runtime representation of a class type. */def classOf[T]: Class[T] = null// this is a dummy, classOf is handled by compiler.// Standard type aliases --------------------------------------------- type String= java.lang.Stringtype Class[T]= java.lang.Class[T]// Miscellaneous -----------------------------------------------------type Function[-A, +B] = Function1[A, B] type Map[A, +B] = collection.immutable.Map[A, B]type Set[A] = collection.immutable.Set[A]val Map = collection.immutable.Mapval Set = collection.immutable.Set// Manifest types, companions, and incantations for summoning --------- type ClassManifest[T] = scala.reflect.ClassManifest[T]type Manifest[T]= scala.reflect.Manifest[T]type OptManifest[T]= scala.reflect.OptManifest[T]val ClassManifest = scala.reflect.ClassManifestval Manifest= scala.reflect.Manifestval NoManifest= scala.reflect.NoManifestdef manifest[T](implicit m: Manifest[T])= m def classManifest[T](implicit m: ClassManifest[T]) = mdef optManifest[T](implicit m: OptManifest[T])= m// Minor variations on identity functions ----------------------------- def identity[A](x: A) : A= x// @see `conforms` for the implicit version-------------------------------------------------------------------------------12.5 The Predef Object 153def implicitly[T](implicit e: T) = e// for summoning implicit values from the nether world@inline def locally[T](x: T) : T= x// to communicate intent and avoid unmoored statements // Asserts, Preconditions, Postconditions -----------------------------def assert(assertion: Boolean) {if (!assertion)throw new java.lang.AssertionError("assertion failed") }def assert(assertion: Boolean, message: => Any) {if (!assertion)throw new java.lang.AssertionError("assertion failed: " + message)}def assume(assumption: Boolean) { if (!assumption)throw new IllegalArgumentException("assumption failed")}def assume(assumption: Boolean, message: => Any) {if (!assumption)throw new IllegalArgumentException(message.toString) }def require(requirement: Boolean) {if (!requirement)throw new IllegalArgumentException("requirement failed")}def require(requirement: Boolean, message: => Any) { if (!requirement)throw new IllegalArgumentException("requirement failed: "+ message)}------------------------------------------------------------------------------- 154The Scala Standard Library// tupling ---------------------------------------------------------type Pair[+A, +B] = Tuple2[A, B]object Pair {def apply[A, B](x: A, y: B) = Tuple2(x, y) def unapply[A, B](x: Tuple2[A, B]) : Option[Tuple2[A, B]] = Some(x)}type Triple[+A, +B, +C] = Tuple3[A, B, C]object Triple {def apply[A, B, C](x: A, y: B, z: C) = Tuple3(x, y, z) def unapply[A, B, C](x: Tuple3[A, B, C]) : Option[Tuple3[A, B, C]] = Some(x)}// Printing and reading -----------------------------------------------def print(x: Any) = Console.print(x) def println() = Console.println()def println(x: Any) = Console.println(x)def printf(text: String, xs: Any*) = Console.printf(text.format(xs: *) )def readLine() : String = Console.readLine() def readLine(text: String, args: Any*) = Console.readLine(text, args)def readBoolean() = Console.readBoolean()def readByte() = Console.readByte()def readShort() = Console.readShort() def readChar() = Console.readChar()def readInt() = Console.readInt()def readLong() = Console.readLong()def readFloat() = Console.readFloat()def readDouble() = Console.readDouble() def readf(format: String) = Console.readf(format)def readf1(format: String) = Console.readf1(format)def readf2(format: String) = Console.readf2(format)def readf3(format: String) = Console.readf3(format) // Implict conversions ------------------------------------------------...}12.5.1 Predefined Implicit DefinitionsThe Predef object also contains a number of implicit definitions, which are avail- able by default (because Predef is implicitly imported) . Implicit definitions come in-------------------------------------------------------------------------------12.5 The Predef Object 155two priorities. High-priority implicits are defined in the Predef class itself whereaslow priority implicits are defined in a class inherited by Predef. The rules of staticoverloading resolution (§6.26.3) stipulate that, all other things being equal, implicit resolution prefers high-priority implicits over low-priority ones.The available low-priority implicits include definitions falling into the following cat-egories.1. For every primitive type, a wrapper that takes values of that type to instances of a runtime.Rich* class. For instance, values of type Int can be implicitlyconverted to instances of class runtime.RichInt.2. For every array type with elements of primitive type, a wrapper that takes the arrays of that type to instances of a runtime.WrappedArray class. For instance,values of type Array[Float] can be implicitly converted to instances of classruntime.WrappedArray[Float]. There are also generic array wrappers that take elements of type Array[T] for arbitrary T to WrappedArrays.3. An implicit conversion from String to WrappedString.The available high-priority implicits include definitions falling into the following categories.· An implicit wrapper that adds ensuring methods with the following over-loaded variants to type Any.def ensuring(cond: Boolean) : A = { assert(cond) ; x }def ensuring(cond: Boolean, msg: Any) : A = { assert(cond, msg) ; x } def ensuring(cond: A => Boolean) : A = { assert(cond(x) ); x }def ensuring(cond: A => Boolean, msg: Any) : A = { assert(cond(x) , msg) ; x }· An implicit wrapper that adds a -> method with the following implementation to type Any.def -> [B](y: B) : (A, B) = (x, y)· For every array type with elements of primitive type, a wrapper that takes thearrays of that type to instances of a runtime.ArrayOps class. For instance, values of type Array[Float] can be implicitly converted to instances of classruntime.ArrayOps[Float]. There are also generic array wrappers that takeelements of type Array[T] for arbitrary T to ArrayOpss. · An implicit wrapper that adds + and formatted method with the followingimplementations to type Any.def +(other: String) = String.valueOf(self) + otherdef formatted(fmtstr: String) : String = fmtstr format self -------------------------------------------------------------------------------156The Scala Standard Library· Numeric primitive conversions that implement the transitive closure of the following mappings:Byte-> ShortShort -> IntChar-> IntInt-> LongLong-> FloatFloat -> Double · Boxing and unboxing conversions between primitive types and their boxedversions:Byte<-> java.lang.ByteShort<-> java.lang.ShortChar <-> java.lang.CharacterInt<-> java.lang.IntegerLong<-> java.lang.LongFloat<-> java.lang.FloatDouble<-> java.lang.Double Boolean <-> java.lang.Boolean· An implicit definition that generates instances of type T <:< T, for any type T.Here, <:< is a class defined as follows.sealed abstract class <:<[-From, +To] extends (From => To) Implicit parameters of <:< types are typically used to implement type con-straints.-------------------------------------------------------------------------------Bibliography [Dra10]Iulian Dragos. Scala specialization, 2010. SID-9.[KP07]Andrew J. Kennedy and Benjamin C. Pierce. On Decidability of NominalSubtyping with Variance, January 2007. FOOL-WOOD '07. [Oa04]Martin Odersky and al. An Overview of the Scala Programming Lan-guage. Technical Report IC/2004/64, EPFL Lausanne, Switzerland, 2004.[OCRZ03] Martin Odersky, Vincent Cremet, Christine Röckl, and Matthias Zenger. A Nominal Theory of Objects with Dependent Types. In Proc. ECOOP'03,Springer LNCS, July 2003.[Ode06]Martin Odersky. The Scala Experiment ­ Can We Provide Better Lan-guage Support for Component Systems? In Proc. ACM Symposium on Principles of Programming Languages, 2006.[OZ05a]Martin Odersky and Matthias Zenger.Independently Extensible So-lutions to the Expression Problem. In Proc. FOOL 12, January 2005. http://homepages.inf.ed.ac.uk/wadler/fool.[OZ05b]Martin Odersky and Matthias Zenger. Scalable Component Abstractions.In Proc. OOPSLA, 2005. [W3C]W3C. Extensible Markup Language (XML) .http://www.w3.org/TR/REC-xml.------------------------------------------------------------------------------- -------------------------------------------------------------------------------Chapter AScala Syntax SummaryThe lexical syntax of Scala is given by the following grammar in EBNF form. upper::=`A' | · · · | `Z' | `$' | `' and Unicode category Lulower::=`a' | · · · | `z' and Unicode category Llletter ::=upper | lower and Unicode categories Lo, Lt, Nldigit::=`0' | · · · | `9'opchar::="all other characters in \u0020-007F and Unicode categories Sm, So except parentheses ([]) and periods"op::=opchar {opchar}varid::=lower idrestplainid::=upper idrest |varid|opid::=plainid|`\`' stringLit `\`'idrest::={letter | digit} [`' op] integerLiteral::=(decimalNumeral | hexNumeral | octalNumeral) [`L' | `l']decimalNumeral::=`0' | nonZeroDigit {digit}hexNumeral::= `0' `x' hexDigit {hexDigit}octalNumeral::=`0' octalDigit {octalDigit}digit::=`0' | nonZeroDigitnonZeroDigit::= `1' | · · · | `9'octalDigit::=`0' | · · · | `7'floatingPointLiteral::=digit {digit} `.' {digit} [exponentPart] [floatType] |`.' digit {digit} [exponentPart] [floatType]|digit {digit} exponentPart [floatType]|digit {digit} [exponentPart] floatTypeexponentPart::= (`E' | `e') [`+' | `-'] digit {digit}floatType::=`F' | `f' | `D' | `d'------------------------------------------------------------------------------- 160Scala Syntax SummarybooleanLiteral::=`true' | `false'characterLiteral ::=`\'' printableChar `\''|`\'' charEscapeSeq `\'' stringLiteral::=`"' {stringElement} `"'|`"""' multiLineChars `"""'stringElement::=printableCharNoDoubleQuote |charEscapeSeqmultiLineChars::={[`"'] [`"'] charNoDoubleQuote} {`"'}symbolLiteral::=`'' plainid comment::=`/*' "any sequence of characters" `*/'|`//' "any sequence of characters up to end of line"nl::="new line character" semi::=`;' |nl {nl}The context-free syntax of Scala is given by the following EBNF grammar.Literal::=[`-'] integerLiteral |[`-'] floatingPointLiteral|booleanLiteral|characterLiteral|stringLiteral|symbolLiteral|`null' QualId::=id {`.' id}ids::=id {`,' id}Path::=StableId|[id `.'] `this'StableId ::=id|Path `.' id|[id '.'] `super' [ClassQualifier] `.' idClassQualifier::=`[' id `]'Type ::=FunctionArgTypes `=>' Type|InfixType [ExistentialClause]FunctionArgTypes::= InfixType| `(' [ ParamType {`,' ParamType } ] `) ' ExistentialClause ::=`forSome' `{' ExistentialDcl {semi ExistentialDcl} `}'ExistentialDcl::=`type' TypeDcl|`val' ValDcl InfixType::=CompoundType {id [nl] CompoundType}CompoundType::=AnnotType {`with' AnnotType} [Refinement]------------------------------------------------------------------------------- 161|RefinementAnnotType::=SimpleType {Annotation}SimpleType::=SimpleType TypeArgs|SimpleType `#' id |StableId|Path `.' `type'|`(' Types ') 'TypeArgs::=`[' Types `]'Types::= Type {`,' Type}Refinement::=[nl] `{' RefineStat {semi RefineStat} `}'RefineStat::=Dcl|`type' TypeDef| TypePat::=TypeAscription::=`:' InfixType|`:' Annotation {Annotation}|`:' `' `*'Expr ::=(Bindings | [`implicit'] id | `') `=>' Expr|Expr1Expr1::=`if' `(' Expr `) ' {nl} Expr [[semi] else Expr]| `while' `(' Expr `) ' {nl} Expr|`try' `{' Block `}' [`catch'`{' CaseClauses `}'][`finally' Expr]|`do' Expr [semi] `while' `(' Expr ') ' |`for' (`(' Enumerators `) ' | `{' Enumerators `}'){nl} [`yield'] Expr|`throw' Expr|`return' [Expr]| [SimpleExpr `.'] id `=' Expr|SimpleExpr1 ArgumentExprs `=' Expr|PostfixExpr|PostfixExpr Ascription|PostfixExpr `match' `{' CaseClauses `}' PostfixExpr::=InfixExpr [id [nl]]InfixExpr::=PrefixExpr|InfixExpr id [nl] InfixExprPrefixExpr::=[`-' | `+' | `~' | `!'] SimpleExpr SimpleExpr::=`new' (ClassTemplate | TemplateBody)|BlockExpr|SimpleExpr1 [`']SimpleExpr1::=Literal| Path|`'|`(' [Exprs] `) '|SimpleExpr `.' id|SimpleExpr TypeArgs|SimpleExpr1 ArgumentExprs -------------------------------------------------------------------------------162Scala Syntax Summary|XmlExprExprs::=Expr {`,' Expr} ArgumentExprs::=`(' [Exprs] `) '|`(' [Exprs `,'] PostfixExpr `:' `' `*' ') '|[nl] BlockExprBlockExpr ::=`{' CaseClauses `}'|`{' Block `}'Block::={BlockStat semi} [ResultExpr]BlockStat::=Import |{Annotation} [`implicit' | `lazy'] Def|{Annotation} {LocalModifier} TmplDef|Expr1|ResultExpr::=Expr1| (Bindings | ([`implicit'] id | `') `:' CompoundType) `=>' BlockEnumerators::=Generator {semi Enumerator}Enumerator::=Generator |Guard|`val' Pattern1 `=' ExprGenerator::=Pattern1 `<-' Expr [Guard]CaseClauses::=CaseClause { CaseClause } CaseClause::=`case' Pattern [Guard] `=>' BlockGuard::=`if' PostfixExprPattern::=Pattern1 { `|' Pattern1 } Pattern1::=varid `:' TypePat|`' `:' TypePat|Pattern2Pattern2::=varid [`@' Pattern3]| Pattern3Pattern3::=SimplePattern|SimplePattern { id [nl] SimplePattern }SimplePattern::=`'|varid |Literal|StableId|StableId `(' [Patterns `) '|StableId `(' [Patterns `,'] [varid `@'] `' `*' `) ' |`(' [Patterns] `) '|XmlPatternPatterns::=Pattern [`,' Patterns]|`' *TypeParamClause::= `[' VariantTypeParam {`,' VariantTypeParam} `]'FunTypeParamClause::=`[' TypeParam {`,' TypeParam} `]'VariantTypeParam::={Annotation} [`+' | `-'] TypeParam TypeParam::=(id | `') [TypeParamClause] [`>:' Type] [`<:' Type]-------------------------------------------------------------------------------163 {`<%' Type} {`:' Type}ParamClauses::={ParamClause} [[nl] `(' `implicit' Params `) ']ParamClause::=[nl] `(' [Params] ') ' Params::=Param {`,' Param}Param::={Annotation} id [`:' ParamType] [`=' Expr]ParamType::=Type|`=>' Type |Type `*'ClassParamClauses ::={ClassParamClause}[[nl] `(' `implicit' ClassParams `) ']ClassParamClause::=[nl] `(' [ClassParams] ') ' ClassParams::=ClassParam {`' ClassParam}ClassParam::={Annotation} [{Modifier} (`val' | `var') ]id `:' ParamType [`=' Expr] Bindings::=`(' Binding {`,' Binding `) 'Binding::=(id | `') [`:' Type]Modifier::=LocalModifier| AccessModifier|`override'LocalModifier::=`abstract'|`final'|`sealed'|`implicit' |`lazy'AccessModifier::=(`private' | `protected') [AccessQualifier]AccessQualifier::=`[' (id | `this') `]' Annotation::=`@' SimpleType {ArgumentExprs}ConstrAnnotation::=`@' SimpleType ArgumentExprsNameValuePair::=`val' id `=' PrefixExpr TemplateBody::=[nl] `{' [SelfType] TemplateStat {semi TemplateStat} `}'TemplateStat::=Import|{Annotation [nl]} {Modifier} Def |{Annotation [nl]} {Modifier} Dcl|Expr|SelfType::=id [`:' Type] `=>'|`this' `:' Type `=>' Import::=`import' ImportExpr {`,' ImportExpr}ImportExpr::=StableId `.' (id | `' | ImportSelectors)ImportSelectors::= `{' {ImportSelector `,'} (ImportSelector | `') `}'ImportSelector::=id [`=>' id | `=>' `']Dcl::=`val' ValDcl |`var' VarDcl|`def' FunDcl-------------------------------------------------------------------------------164Scala Syntax Summary| `type' {nl} TypeDclValDcl::=ids `:' TypeVarDcl::=ids `:' TypeFunDcl::=FunSig [`:' Type]FunSig ::=id [FunTypeParamClause] ParamClausesTypeDcl::=id [TypeParamClause] [`>:' Type] [`<:' Type]PatVarDef::=`val' PatDef |`var' VarDefDef::=PatVarDef|`def' FunDef|`type' {nl} TypeDef|TmplDefPatDef ::=Pattern2 {`,' Pattern2} [`:' Type] `=' ExprVarDef::=PatDef|ids `:' Type `=' `'FunDef::=FunSig [`:' Type] `=' Expr |FunSig [nl] `{' Block `}'|`this' ParamClause ParamClauses(`=' ConstrExpr | [nl] ConstrBlock)TypeDef::=id [TypeParamClause] `=' Type TmplDef::=[`case'] `class' ClassDef|[`case'] `object' ObjectDef|`trait' TraitDefClassDef::=id [TypeParamClause] {ConstrAnnotation} [AccessModifier] ClassParamClauses ClassTemplateOptTraitDef::=id [TypeParamClause] TraitTemplateOptObjectDef::=id ClassTemplateOptClassTemplateOpt ::=`extends' ClassTemplate | [[`extends'] TemplateBody]TraitTemplateOpt::=`extends' TraitTemplate | [[`extends'] TemplateBody]ClassTemplate ::=[EarlyDefs] ClassParents [TemplateBody]TraitTemplate::=[EarlyDefs] TraitParents [TemplateBody]ClassParents::=Constr {`with' AnnotType} TraitParents::=AnnotType {`with' AnnotType}Constr::=AnnotType {ArgumentExprs}EarlyDefs::= `{' [EarlyDef {semi EarlyDef}] `}' `with' EarlyDef::={Annotation [nl]} {Modifier} PatVarDefConstrExpr::=SelfInvocation|ConstrBlockConstrBlock::=`{' SelfInvocation {semi BlockStat} `}' SelfInvocation::=`this' ArgumentExprs {ArgumentExprs}TopStatSeq::=TopStat {semi TopStat}TopStat::={Annotation [nl]} {Modifier} TmplDef |Import|Packaging-------------------------------------------------------------------------------165|PackageObject|Packaging ::=`package' QualId [nl] `{' TopStatSeq `}'PackageObject::=`package' `object' ObjectDefCompilationUnit::={`package' QualId semi} TopStatSeq --------------------------------------------------------------------------------------------------------------------------------------------------------------Chapter BChange Log Changes in Version 2.8.0Trailing commasTrailing commas in expression, argument, type or pattern sequences are no longersupported.Changes in Version 2.8 (under development) Changed visibility rules for nested packages (where done?)Changed visibility rules in §2so that packages are no longer treated specially.Added section §3.5.3on weak conformance. Relaxed type rules for conditionals, match expressions, try expressions to compute their result type using least upperbound wrt weak conformance. Relaxed type rule for local type inference so that ar-gument types need only weekly conform to inferred formal parameter types. Added section on numeric widening in §6.26to support weak conformance.Tightened rules to avpod accidential overrides in §5.1.4.Removed class literals.Added section §7.4on context bounds. Clarified differences between isInstanceOf and pattern matches (§12.1) .Allowed implicit modifier on function literals with a single parameter (§6.23) .------------------------------------------------------------------------------- 168Change LogChanges in Version 2.7.2 (10-Nov-2008Precedence of Assignment OperatorsThe precedence of assignment operators has been brought in line with Java's (§6.12) .From now on, += has the same precedence as =.Wildcards as function parametersA formal parameter to an anonymous fucntion may now be a wildcard representedby an underscore (§6.23) .Example: _ => 7// The function that ignores its argument// and always returns 7.Unicode alternative for left arrowThe Unicode glyph \u2190 `' is now treated as a reserved identifier, equivalent to the ASCII symbol `<-'.Changes in Version 2.7.1 (09-April-2008)Change in Scoping Rules for Wildcard Placeholders in TypesA wildcard in a type now binds to the closest enclosing type application. For exam- ple List[List[]] is now equivalent to the existential typeList[List[t] forSome { type t }] .In version 2.7.0, the type expanded instead toList[List[t]] forSome { type t } . The new convention corresponds exactly to the way wildcards in Java are inter-preted.No Contractiveness Requirement for ImplicitsThe contractiveness requirement for implicit method definitions has been dropped. Instead it is checked for each implicit expansion individually that the expansiondoes not result in a cycle or a tree of infinitely growing types (§7.2) .------------------------------------------------------------------------------- 169Changes in Version 2.7.0 (07-Feb-2008)Java GenericsScala now supports Java generic types by default:· A generic type in Java such as ArrayList<String> is translated to a generic type in Scala: ArrayList[String].· A wildcard type such as ArrayList<? extends Number> is translated toArrayList[_ <: Number]. This is itself a shorthand for the existential type ArrayList[T] forSome { type T <: Number }.· A raw type in Java such as ArrayList is translated to ArrayList[], which is ashorthand for ArrayList[T] forSome { type T }.This translation works if -target:jvm-1.5 is specified, which is the new default. For any other target, Java generics are not recognized. To ensure upgradability of Scalacodebases, extraneous type parameters for Java classes under -target:jvm-1.4are simply ignored. For instance, when compiling with -target:jvm-1.4, a Scala type such as ArrayList[String] is simply treated as the unparameterized typeArrayList.Changes to Case ClassesThe Scala compiler generates now for every case class a companion extractor object (§5.3.2) .For instance, given the case class:case class X(elem: String)the following companion object is generated:object X {def unapply(x: X) : Some[String] = Some(x.elem) def apply(s: String) : X = new X(s)}If the object exists already, only the apply and unapply methods are added to it.Three restrictions on case classes have been removed.1. Case classes can now inherit from other case classes. 2. Case classes may now be abstract.3. Case classes may now come with companion objects.-------------------------------------------------------------------------------170Change Log Changes in Version 2.6.1 (30-Nov-2007)Mutable variables introduced by pattern bindingMutable variables can now be introduced by a pattern matching definition (§4.2) ,just like values can. Examples: var (x, y) = if (positive) (1, 2) else (-1, -3)var hd :: tl = mylistSelf-typesSelf types can now be introduced without defining an alias name for this (§5.1) .Example: class C {type T <: Traittrait Trait { this: T => ... }}Changes in Version 2.6 (27-July-2007)Existential typesIt is now possible to define existential types (§3.2.10) .An existential type has the form T forSome {Q} where Q is a sequence of value and/or type declarations. Giventhe class definitionsclass Ref[T]abstract class Outer { type T }one may for example write the following existential types Ref[T] forSome { type T <: java.lang.Number }Ref[x.T] forSome { val x: Outer }Lazy valuesIt is now possible to define lazy value declarations using the new modifier lazy (§4.1) .A lazy value definition evaluates its right hand side e the first time the valueis accessed. Example:import compat.Platform._val t0 = currentTimelazy val t1 = currentTime -------------------------------------------------------------------------------171val t2 = currentTimeprintln("t0 <= t2: " + (t0 <= t2) )//trueprintln("t1 <= t2: " + (t1 <= t2) ) //false (lazy evaluation of t1)Structural typesIt is now possible to declare structural types using type refinements (§3.2.7) .Forexample:class File(name: String) { def getName() : String = namedef open() { /*..*/ }def close() { println("close file") }}def test(f: { def getName() : String }) { println(f.getName) }test(new File("test.txt") ) test(new java.io.File("test.txt") )There's also a shorthand form for creating values of structural types. For instance,new { def getName() = "aaron" }is a shorthand for new AnyRef{ def getName() = "aaron" }Changes in Version 2.5 (02-May-2007)Type constructor polymorphism1Type parameters (§4.4) and abstract type members (§4.3) can now also abstract over type constructors (§3.3.3) .This allows a more precise Iterable interface:trait Iterable[+T] {type MyType[+T] <: Iterable[T] // MyType is a type constructordef filter(p: T => Boolean) : MyType[T] = ... def map[S](f: T => S) : MyType[S] = ...}1Implemented by Adriaan Moors-------------------------------------------------------------------------------172Change Log abstract class List[+T] extends Iterable[T] {type MyType[+T] = List[T]}This definition of Iterable makes explicit that mapping a function over a certainstructure (e.g., a List) will yield the same structure (containing different elements) . Early object initializationIt is now possible to initialize some fields of an object before any parent constructorsare called (§5.1.6) .This is particularly useful for traits, which do not have normal constructor parameters. Example:trait Greeting {val name: Stringval msg = "How are you, "+name}class C extends {val name = "Bob" } with Greeting {println(msg)}In the code above, the field name is initialized before the constructor of Greetingis called.Therefore, field msg in class Greeting is properly initialized to "How are you, Bob".For-comprehensions, revisedThe syntax of for-comprehensions has changed (§6.19) .In the new syntax, gener-ators do not start with a val anymore, but filters start with an if (and are called guards) . A semicolon in front of a guard is optional. For example:for (val x <- List(1, 2, 3) ; x % 2 == 0) println(x)is now writtenfor (x <- List(1, 2, 3) if x % 2 == 0) println(x) The old syntax is still available but will be deprecated in the future.Implicit anonymous functionsIt is now possible to define anonymous functions using underscores in parameterposition (§Example 6.23.1) .For instance, the expressions in the left column are each function values which expand to the anonymous functions on their right.-------------------------------------------------------------------------------173_ + 1x => x + 1 _ * _(x1, x2) => x1 * x2(: int) * 2(x: int) => (x: int) * 2if () x else yz => if (z) x else y.map(f)x => x.map(f).map(_ + 1) x => x.map(y => y + 1)As a special case (§6.7) ,a partially unapplied method is now designated m _ insteadof the previous notation &m.The new notation will displace the special syntax forms .m() for abstracting over method receivers and &m for treating an unapplied method as a function value. Forthe time being, the old syntax forms are still available, but they will be deprecatedin the future. Pattern matching anonymous functions, refinedIt is now possible to use case clauses to define a function value directly for functionsof arities greater than one (§8.5) .Previously, only unary functions could be defined that way. Example:def scalarProduct(xs: Array[Double], ys: Array[Double]) =(0.0 /: (xs zip ys) ) {case (a, (b, c) ) => a + b * c}Changes in Version 2.4 (09-Mar-2007) Object-local private and protectedThe private and protected modifiers now accept a [this] qualifier (§5.2) .A defini-tion M which is labelled private[this] is private, and in addition can be accessed only from within the current object. That is, the only legal prefixes for M are thisor C .this. Analogously, a definition M which is labelled protected[this] is pro-tected, and in addition can be accessed only from within the current object. Tuples, revisedThe syntax for tuples has been changed from {. . .} to (. . .) (§6.9) .For any sequence oftypes T1, ..., Tn,(T1, ..., Tn)is a shorthand forTuplen[T1, . . . , Tn]. Analogously, for any sequence of expressions or patterns x1, ..., xn,(x1, ..., xn)is a shorthand forTuplen(x1, . . . , xn) .------------------------------------------------------------------------------- 174Change LogAccess modifiers for primary constructorsThe primary constructor of a class can now be marked private or protected (§5.3) .If such an access modifier is given, it comes between the name of the class and its value parameters. Example:class C[T] private (x: T) { ... }AnnotationsThe support for attributes has been extended and its syntax changed (§11) .At-tributes are now called annotations. The syntax has been changed to follow Java's conventions, e.g. @attribute instead of [attribute]. The old syntax is still avail-able but will be deprecated in the future.Annotations are now serialized so that they can be read by compile-time or run- time tools. Class scala.Annotation has two sub-traits which are used to indicatehow annotations are retained. Instances of an annotation class inheriting from traitscala.ClassfileAnnotation will be stored in the generated class files. Instances of an annotation class inheriting from trait scala.StaticAnnotation will be visibleto the Scala type-checker in every compilation unit where the annotated symbol isaccessed.Decidable subtyping The implementation of subtyping has been changed to prevent infinite recursions.Termination of subtyping is now ensured by a new restriction of class graphs to befinitary (§5.1.5) .Case classes cannot be abstract It is now explicitly ruled out that case classes can be abstract (§5.2) .The specifica-tion was silent on this point before, but did not explain how abstract case classeswere treated. The Scala compiler allowed the idiom. New syntax for self aliases and self typesIt is now possible to give an explicit alias name and/or type for the self referencethis (§5.1) .For instance, inclass C { self: D => ...}the name self is introduced as an alias for this within C and the self type (§5.3) of Cis assumed to be D. This construct is introduced now in order to replace eventually -------------------------------------------------------------------------------175both the qualified this construct C.this and the requires clause in Scala.Assignment OperatorsIt is now possible to combine operators with assignments (§6.12.4) .Example: var x: int = 0x += 1Changes in Version 2.3.2 (23-Jan-2007)ExtractorsIt is now possible to define patterns independently of case classes, using unapplymethods in extractor objects (§8.1.8) .Here is an example: object Twice {def apply(x:Int) : int = x*2def unapply(z:Int) : Option[int] = if (z%2==0) Some(z/2) else None}val x = Twice(21)x match { case Twice(n) => Console.println(n) } // prints 21 In the example, Twice is an extractor object with two methods:· The apply method is used to build even numbers.· The unapply method is used to decompose an even number; it is in a sense the reverse of apply. unapply methods return option types: Some(...) for amatch that suceeds, None for a match that fails. Pattern variables are returnedas the elements of Some. If there are several variables, they are grouped in a tuple.In the second-to-last line, Twice's apply method is used to construct a number x.In the last line, x is tested against the pattern Twice(n) . This pattern succeeds foreven numbers and assigns to the variable n one half of the number that was tested. The pattern match makes use of the unapply method of object Twice. More detailson extractors can be found in the paper "Matching Objects with Patterns" by Emir,Odersky and Williams. TuplesA new lightweight syntax for tuples has been introduced (§6.9) .For any sequence oftypes T1, ..., Tn,{T1, ..., Tn}is a shorthand forTuplen[T1, . . . , Tn]. -------------------------------------------------------------------------------176Change LogAnalogously, for any sequence of expressions or patterns x1, ..., xn,{x1, ..., xn} is a shorthand forTuplen(x1, . . . , xn) .Infix operators of greater aritiesIt is now possible to use methods which have more than one parameter as infixoperators (§6.12) .In this case, all method arguments are written as a normal pa- rameter list in parentheses. Example:class C {def +(x: int, y: String) = ...}val c = new Cc + (1, "abc")Deprecated attributeA new standard attribute deprecated is available (§11) .If a member definition is marked with this attribute, any reference to the member will cause a "deprecated"warning message to be emitted.Changes in Version 2.3 (23-Nov-2006)ProceduresA simplified syntax for functions returning unit has been introduced (§4.6.3) .Scala now allows the following shorthands:def f(params)fordef f(params) : unitdef f(params) { ... }fordef f(params) : unit = { ... }Type Patterns The syntax of types in patterns has been refined (§8.2) .Scala now distinguishes be-tween type variables (starting with a lower case letter) and types as type argumentsin patterns. Type variables are bound in the pattern. Other type arguments are, as in previous versions, erased. The Scala compiler will now issue an "unchecked"warning at places where type erasure might compromise type-safety.Standard TypesThe recommended names for the two bottom classes in Scala's type hierarchy have changed as follows:-------------------------------------------------------------------------------177All==>NothingAllRef==> NullThe old names are still available as type aliases.Changes in Version 2.1.8 (23-Aug-2006)Visibility Qualifier for protectedProtectedmemberscan nowhaveavisibilityqualifier(§5.2) ,e.g.protected[<qualifier>]. In particular, one can now simulate package protectedaccess as in Java writing protected[P] def X ...where P would name the package containing X.Relaxation of Private AcessPrivate members of a class can now be referenced from the companion module ofthe class and vice versa (§5.2) Implicit LookupThe lookup method for implicit definitions has been generalized (§7.2) .Whensearching for an implicit definition matching a type T , now are considered1. all identifiers accessible without prefix, and 2. all members of companion modules of classes associated with T .(The second clause is more general than before) . Here, a class is associated with atype T if it is referenced by some part of T , or if it is a base class of some part of T . For instance, to find implicit members corresponding to the typeHashSet[List[Int], String]one would now look in the companion modules (aka static parts) of HashSet, List,Int, and String. Before, it was just the static part of HashSet. Tightened Pattern MatchA typed pattern match with a singleton type p.type now tests whether the selectorvalue is reference-equal to p (§8.1) .Example:val p = List(1, 2, 3)------------------------------------------------------------------------------- 178Change Logval q = List(1, 2)val r = qr match {case : p.type => Console.println("p")case : q.type => Console.println("q") }This will match the second case and hence will print "q". Before, the singleton typeswere erased to List, and therefore the first case would have matched, which is non-sensical. Changes in Version 2.1.7 (19-Jul-2006)Multi-Line string literalsIt is now possible to write multi-line string-literals enclosed in triple quotes (§1.3.5) .Example:"""this is a multi-linestring literal"""No escape substitutions except for unicode escapes are performed in such stringliterals.Closure SyntaxThe syntax of closures has been slightly restricted (§6.23) .The form x: T => Eis valid only when enclosed in braces, i.e. { x: T => E }. The following is illegal,because it might be read as the value x typed with the type T => E:val f = x: T => E Legal alternatives are:val f = { x: T => E }val f = (x: T) => E-------------------------------------------------------------------------------179Changes in Version 2.1.5 (24-May-2006) Class LiteralsThere is a new syntax for class literals (§6.2) :For any class type C , classOf[C ] des-ignates the run-time representation of C .Changes in Version 2.0 (12-Mar-2006) Scala in its second version is different in some details from the first version of thelanguage. There have been several additions and some old idioms are no longersupported. This appendix summarizes the main changes. New KeywordsThe following three words are now reserved; they cannot be used as identifiers (§1.1)implicitmatchrequiresNewlines as Statement Separators Newlines can now be used as statement separators in place of semicolons (§1.2)Syntax RestrictionsThere are some other situations where old constructs no longer work:Pattern matching expressions. The match keyword now appears only as infix op-erator between a selector expression and a number of cases, as in:expr match {case Some(x) => ...case None => ... }Variants such as expr.match {...} or just match {...} are no longer sup-ported."With" in extends clauses.. The idiomclass C with M { ... }is no longer supported. A with connective is only allowed following an extends clause. For instance, the line above would have to be written-------------------------------------------------------------------------------180Change Logclass C extends AnyRef with M { ... } . However, assuming M is a trait (see 5.3.3) ,it is also legal to writeclass C extends M { ... }The latter expression is treated as equivalent toclass C extends S with M { ... } where S is the superclass of M.Regular Expression Patterns.The only form of regular expression pattern that iscurrently supported is a sequence pattern, which might end in a sequence wildcard *. Example:case List(1, 2, *) => ... // will match all lists starting with \code{1,2}.It is at current not clear whether this is a permanent restriction. We are evaluatingthe possibility of re-introducing full regular expression patterns in Scala. Selftype AnnotationsThe recommended syntax of selftype annotations has changed.class C: T extends B { ... }becomesclass C requires T extends B { ... }That is, selftypes are now indicated by the new requires keyword. The old syntax is still available but is considered deprecated.For-comprehensionsFor-comprehensions (§6.19) now admit value and pattern definitions. Example:for {val x <- List.range(1, 100) val y <- List.range(1, x)val z = x + yisPrime(z)} yield Pair(x, y)Note the definition val z = x + y as the third item in the for-comprehension.------------------------------------------------------------------------------- 181ConversionsThe rules for implicit conversions of methods to functions (§6.26) have been tight-ened. Previously, a parameterized method used as a value was always implicitly converted to a function. This could lead to unexpected results when method argu-ments where forgotten. Consider for instance the statement below:show(x.toString)where show is defined as follows: def show(x: String) = Console.println(x) .Most likely, the programmer forgot to supply an empty argument list () to toString.The previous Scala version would treat this code as a partially applied method, and expand it to:show(() => x.toString() )As a result, the address of a closure would be printed instead of the value of s.Scala version 2.0 will apply a conversion from partially applied method to function value only if the expected type of the expression is indeed a function type. For in-stance, the conversion would not be applied in the code above because the expectedtype of show's parameter is String, not a function type. The new convention disallows some previously legal code. Example:def sum(f: int => double) (a: int, b: int) : double =if (a > b) 0 else f(a) + sum(f) (a + 1, b)val sumInts =sum(x => x)// error: missing argumentsThe partial application of sum in the last line of the code above will not be convertedto a function type. Instead, the compiler will produce an error message which states that arguments for method sum are missing. The problem can be fixed by providingan expected type for the partial application, for instance by annotating the defini-tion of sumInts with its type: val sumInts: (int, int) => double=sum(x => x)// OKOn the other hand, Scala version 2.0 now automatically applies methods with emptyparameter lists to () argument lists when necessary. For instance, the show expres- sion above will now be expanded toshow(x.toString() ) .Scala version 2.0 also relaxes the rules of overriding with respect to empty parameterlists. The revised definition of matching members (§5.1.3) makes it now possible to -------------------------------------------------------------------------------182Change Logoverride a method with an explicit, but empty parameter list () with a parameterless method, and vice versa. For instance, the following class definition is now legal:class C {override def toString: String = ...}Previously this definition would have been rejected, because the toString method as inherited from java.lang.Object takes an empty parameter list.Class ParametersA class parameter may now be prefixed by val or var (§5.3) .Private QualifiersPreviously, Scala had three levels of visibility: private, protected and public. There was no way to restrict accesses to members of the current package, as in Java. Scala2 now defines access qualifiers that let one express this level of visibility, amongothers. In the definition private[C] def f(...)access to f is restricted to all code within the class or package C (which must containthe definition of f) (§5.2)Changes in the Mixin ModelThe model which details mixin composition of classes has changed significantly. The main differences are:1. We now distinguish between traits that are used as mixin classes and normalclasses. The syntax of traits has been generalized from version 1.0, in thattraits are now allowed to have mutable fields. However, as in version 1.0, traits still may not have constructor parameters.2. Member resolution and super accesses are now both defined in terms of aclass linearization.3. Scala's notion of method overloading has been generalized; in particular, it is now possible to have overloaded variants of the same method in a subclassand in a superclass, or in several different mixins. This makes method over-loading in Scala conceptually the same as in Java. The new mixin model is explained in more detail in §5.-------------------------------------------------------------------------------183Implicit ParametersViews in Scala 1.0 have been replaced by the more general concept of implicit pa- rameters (§7)Flexible Typing of Pattern MatchingThe new version of Scala implements more flexible typing rules when it comes topattern matching over heterogeneous class hierarchies (§8.4) .A heterogeneous class hierarchy is one where subclasses inherit a common superclass with different pa-rameter types. With the new rules in Scala version 2.0 one can perform patternmatches over such hierarchies with more precise typings that keep track of the infor- mation gained by comparing the types of a selector and a matching pattern (§Exam-ple 8.4.1) .This gives Scala capabilities analogous to guarded algebraic data types.-------------------------------------------------------------------------------

DDooccuummeenntt OOuuttlliinnee

* Lexical Syntax
  o Identifiers  o Newline Characters   o Literals
    # Integer Literals    # Floating Point Literals    # Boolean Literals    # Character Literals    # String Literals    # Escape Sequences     # Symbol literals
  o Whitespace and Comments  o XML mode
* Identifiers, Names and Scopes* Types
  o Paths   o Value Types
    # Singleton Types    # Type Projection    # Type Designators    # Parameterized Types    # Tuple Types    # Annotated Types     # Compound Types    # Infix Types    # Function Types    # Existential Types
  o Non-Value Types
    # Method Types    # Polymorphic Method Types     # Type Constructors
  o Base Types and Member Definitions  o Relations between types
    # Type Equivalence    # Conformance    # Weak Conformance
  o Volatile Types  o Type Erasure
* Basic Declarations and Definitions
  o Value Declarations and Definitions  o Variable Declarations and Definitions   o Type Declarations and Type Aliases  o Type Parameters  o Variance Annotations  o Function Declarations and Definitions
    # By-Name Parameters     # Repeated Parameters    # Procedures    # Method Return Type Inference
  o Import Clauses
* Classes and Objects
  o Templates
    # Constructor Invocations    # Class Linearization    # Class Members    # Overriding    # Inheritance Closure    # Early Definitions
  o Modifiers  o Class Definitions
    # Constructor Definitions    # Case Classes    # Traits
  o Object Definitions
* Expressions
  o Expression Typing  o Literals  o The Null Value  o Designators  o This and Super  o Function Applications
    # Named and Default Arguments
  o Method Values  o Type Applications  o Tuples  o Instance Creation Expressions  o Blocks   o Prefix, Infix, and Postfix Operations
    # Prefix Operations    # Postfix Operations    # Infix Operations    # Assignment Operators
  o Typed Expressions  o Annotated Expressions  o Assignments  o Conditional Expressions  o While Loop Expressions  o Do Loop Expressions  o For Comprehensions and For Loops   o Return Expressions  o Throw Expressions  o Try Expressions  o Anonymous Functions  o Constant Expressions  o Statements  o Implicit Conversions
    # Value Conversions    # Method Conversions    # Overloading Resolution    # Local Type Inference    # Eta Expansion

* Implicit Parameters and Views
  o The Implicit Modifier  o Implicit Parameters  o Views  o Context Bounds and View Bounds  o Manifests
* Pattern Matching
  o Patterns
    # Variable Patterns    # Typed Patterns    # Pattern Binders    # Literal Patterns    # Stable Identifier Patterns     # Constructor Patterns    # Tuple Patterns    # Extractor Patterns    # Pattern Sequences    # Infix Operation Patterns    # Pattern Alternatives    # XML Patterns     # Regular Expression Patterns    # Irrefutable Patterns
  o Type Patterns  o Type Parameter Inference in Patterns  o Pattern Matching Expressions   o Pattern Matching Anonymous Functions
* Top-Level Definitions
  o Compilation Units  o Packagings  o Package Objects  o Package References   o Programs
* XML expressions and patterns
  o XML expressions  o XML patterns
* User-Defined Annotations* The Scala Standard Library
  o Root Classes  o Value Classes
    # Numeric Value Types    # Class [flexiblecolumns=true,basicstyle=]£Boolean£    # Class [flexiblecolumns=true,basicstyle=]£Unit£
  o Standard Reference Classes
    # Class [flexiblecolumns=true,basicstyle=]£String£    # The [flexiblecolumns=true,basicstyle=]£Tuple£ classes    # The [flexiblecolumns=true,basicstyle=]£Function£ Classes     # Class [flexiblecolumns=true,basicstyle=]£Array£
  o Class Node  o The [flexiblecolumns=true,basicstyle=]£Predef£ Object
    # Predefined Implicit Definitions

* Scala Syntax Summary* Change Log
-------------------------------------------------------------------------------
Viktor Klang
Joined: 2008-12-17,
User offline. Last seen 1 year 27 weeks ago.
Re: Text version of Scala Language Specification
Completely recommend going the same route as Akka with compiled sample code pulled into reST documents.
Cheers,√

On Wed, Dec 21, 2011 at 7:58 PM, Paul Phillips <paulp [at] improving [dot] org> wrote:
In case I am not alone in having been driven all the way up the wall and over the nearby cliff in my attempts to cut and paste from the scala specification without devastating the meaning of the paste, I offer the attached plain text version of the scala spec.  It is not perfect, but it is a huge leap forward for me.
It is based on the nightly PDF of today, and is the product of the following successively applied transformations:
 - pdftohtml - htmltotext - me and my text processing friends manually cleaning up a bit until I lost the will to continue
I don't intend to do this again, so the language is frozen right there for all eternity unless someone else wants to make this less of a one-shot thing and/or tell me how to accomplish the same thing on OSX with less manual intervention.

The Scala LanguageSpecificationVersion 2.10DRAFTDecember 21, 2011Martin OderskyPROGRAMMING METHODS LABORATORY EPFLSWITZERLAND

Contents
1 Lexical Syntax   31.1 Identifiers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 1.2 Newline Characters. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51.3 Literals. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81.3.1 Integer Literals. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 1.3.2 Floating Point Literals. . . . . . . . . . . . . . . . . . . . . . . . . 91.3.3 Boolean Literals. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101.3.4 Character Literals. . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 1.3.5 String Literals. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101.3.6 Escape Sequences. . . . . . . . . . . . . . . . . . . . . . . . . . . 121.3.7 Symbol literals. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 1.4 Whitespace and Comments. . . . . . . . . . . . . . . . . . . . . . . . . . 131.5 XML mode. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2 Identifiers, Names and Scopes  15
3 Types  19 3.1 Paths. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203.2 Value Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 3.2.1 Singleton Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213.2.2 Type Projection. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213.2.3 Type Designators. . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 3.2.4 Parameterized Types. . . . . . . . . . . . . . . . . . . . . . . . . . 223.2.5 Tuple Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233.2.6 Annotated Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 3.2.7 Compound Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . 233.2.8 Infix Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253.2.9 Function Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 3.2.10 Existential Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . 263.3 Non-Value Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283.3.1 Method Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 3.3.2 Polymorphic Method Types. . . . . . . . . . . . . . . . . . . . . . 293.3.3 Type Constructors. . . . . . . . . . . . . . . . . . . . . . . . . . . 293.4 Base Types and Member Definitions. . . . . . . . . . . . . . . . . . . . . 29 3.5 Relations between types. . . . . . . . . . . . . . . . . . . . . . . . . . . . 313.5.1 Type Equivalence. . . . . . . . . . . . . . . . . . . . . . . . . . . . 313.5.2 Conformance. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 3.5.3 Weak Conformance. . . . . . . . . . . . . . . . . . . . . . . . . . . 343.6 Volatile Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353.7 Type Erasure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
4 Basic Declarations and Definitions  374.1 Value Declarations and Definitions. . . . . . . . . . . . . . . . . . . . . 384.2 Variable Declarations and Definitions. . . . . . . . . . . . . . . . . . . . 39 4.3 Type Declarations and Type Aliases. . . . . . . . . . . . . . . . . . . . . 414.4 Type Parameters. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 434.5 Variance Annotations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44 4.6 Function Declarations and Definitions. . . . . . . . . . . . . . . . . . . 464.6.1 By-Name Parameters. . . . . . . . . . . . . . . . . . . . . . . . . . 474.6.2 Repeated Parameters. . . . . . . . . . . . . . . . . . . . . . . . . . 48 4.6.3 Procedures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 494.6.4 Method Return Type Inference. . . . . . . . . . . . . . . . . . . . 504.7 Import Clauses. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
5 Classes and Objects  535.1 Templates. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 535.1.1 Constructor Invocations. . . . . . . . . . . . . . . . . . . . . . . . 55 5.1.2 Class Linearization. . . . . . . . . . . . . . . . . . . . . . . . . . . 565.1.3 Class Members. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 575.1.4 Overriding. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58 5.1.5 Inheritance Closure. . . . . . . . . . . . . . . . . . . . . . . . . . 595.1.6 Early Definitions. . . . . . . . . . . . . . . . . . . . . . . . . . . . 605.2 Modifiers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61 5.3 Class Definitions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 645.3.1 Constructor Definitions. . . . . . . . . . . . . . . . . . . . . . . . 665.3.2 Case Classes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67 5.3.3 Traits. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 695.4 Object Definitions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
6 Expressions  73 6.1 Expression Typing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 746.2 Literals. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 746.3 The Null Value. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75 6.4 Designators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 756.5 This and Super . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 766.6 Function Applications. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77 6.6.1 Named and Default Arguments. . . . . . . . . . . . . . . . . . . . 796.7 Method Values. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 806.8 Type Applications. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81 6.9 Tuples. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 816.10 Instance Creation Expressions. . . . . . . . . . . . . . . . . . . . . . . . 816.11 Blocks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82 6.12 Prefix, Infix, and Postfix Operations. . . . . . . . . . . . . . . . . . . . . 836.12.1 Prefix Operations. . . . . . . . . . . . . . . . . . . . . . . . . . . . 846.12.2 Postfix Operations. . . . . . . . . . . . . . . . . . . . . . . . . . . 84 6.12.3 Infix Operations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 846.12.4 Assignment Operators. . . . . . . . . . . . . . . . . . . . . . . . . 856.13 Typed Expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86 6.14 Annotated Expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 866.15 Assignments. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 866.16 Conditional Expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . 88 6.17 While Loop Expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . 886.18 Do Loop Expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 886.19 For Comprehensions and For Loops. . . . . . . . . . . . . . . . . . . . . 89 6.20 Return Expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 916.21 Throw Expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 926.22 Try Expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92 6.23 Anonymous Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 936.24 Constant Expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 956.25 Statements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 6.26 Implicit Conversions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 966.26.1 Value Conversions. . . . . . . . . . . . . . . . . . . . . . . . . . . 966.26.2 Method Conversions. . . . . . . . . . . . . . . . . . . . . . . . . . 97 6.26.3 Overloading Resolution. . . . . . . . . . . . . . . . . . . . . . . . 976.26.4 Local Type Inference. . . . . . . . . . . . . . . . . . . . . . . . . . 1006.26.5 Eta Expansion. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
7 Implicit Parameters and Views  1057.1 The Implicit Modifier. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1057.2 Implicit Parameters. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106 7.3 Views. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1097.4 Context Bounds and View Bounds. . . . . . . . . . . . . . . . . . . . . . 1107.5 Manifests. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
8 Pattern Matching  1138.1 Patterns. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1138.1.1 Variable Patterns. . . . . . . . . . . . . . . . . . . . . . . . . . . . 114 8.1.2 Typed Patterns. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1148.1.3 Pattern Binders. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1148.1.4 Literal Patterns. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 8.1.5 Stable Identifier Patterns. . . . . . . . . . . . . . . . . . . . . . . 1158.1.6 Constructor Patterns. . . . . . . . . . . . . . . . . . . . . . . . . . 1158.1.7 Tuple Patterns. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116 8.1.8 Extractor Patterns. . . . . . . . . . . . . . . . . . . . . . . . . . . . 1168.1.9 Pattern Sequences. . . . . . . . . . . . . . . . . . . . . . . . . . . 1178.1.10 Infix Operation Patterns. . . . . . . . . . . . . . . . . . . . . . . . 117 8.1.11 Pattern Alternatives. . . . . . . . . . . . . . . . . . . . . . . . . . 1188.1.12 XML Patterns. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1188.1.13 Regular Expression Patterns. . . . . . . . . . . . . . . . . . . . . . 118 8.1.14 Irrefutable Patterns. . . . . . . . . . . . . . . . . . . . . . . . . . . 1188.2 Type Patterns. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1198.3 Type Parameter Inference in Patterns. . . . . . . . . . . . . . . . . . . . 119 8.4 Pattern Matching Expressions. . . . . . . . . . . . . . . . . . . . . . . . . 1228.5 Pattern Matching Anonymous Functions. . . . . . . . . . . . . . . . . . 124
9 Top-Level Definitions  127 9.1 Compilation Units. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1279.2 Packagings. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1289.3 Package Objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128 9.4 Package References. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1299.5 Programs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
10 XML expressions and patterns  13110.1 XML expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13110.2 XML patterns. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
11 User-Defined Annotations  135
12 The Scala Standard Library  13912.1 Root Classes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139 12.2 Value Classes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14112.2.1 Numeric Value Types. . . . . . . . . . . . . . . . . . . . . . . . . . 14212.2.2 Class Boolean. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145 12.2.3 Class Unit. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14512.3 Standard Reference Classes. . . . . . . . . . . . . . . . . . . . . . . . . . 14512.3.1 Class String. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146 12.3.2 The Tuple classes. . . . . . . . . . . . . . . . . . . . . . . . . . 14612.3.3 The Function Classes. . . . . . . . . . . . . . . . . . . . . . . 14612.3.4 Class Array. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147 12.4 Class Node. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14912.5 The Predef Object. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15212.5.1 Predefined Implicit Definitions. . . . . . . . . . . . . . . . . . . . 154
A Scala Syntax Summary  159B Change Log  167
1PrefaceScala is a Java-like programming language which unifies object-oriented and func- tional programming. It is a pure object-oriented language in the sense that everyvalue is an object. Types and behavior of objects are described by classes. Classescan be composed using mixin composition. Scala is designed to work seamlessly with two less pure but mainstream object-oriented languages ­ Java and C#.Scala is a functional language in the sense that every function is a value. Nesting offunction definitions and higher-order functions are naturally supported. Scala also supports a general notion of pattern matching which can model the algebraic typesused in many functional languages.Scala has been designed to interoperate seamlessly with Java (an alternative imple- mentation of Scala also works for .NET) . Scala classes can call Java methods, createJava objects, inherit from Java classes and implement Java interfaces. None of thisrequires interface definitions or glue code. Scala has been developed from 2001 in the programming methods laboratory atEPFL. Version 1.0 was released in November 2003. This document describes thesecond version of the language, which was released in March 2006. It acts a refer- ence for the language definition and some core library modules. It is not intended toteach Scala or its concepts; for this there are other documents [Oa04, Ode06, OZ05b,OCRZ03, OZ05a]. Scala has been a collective effort of many people. The design and the implementa-tion of version 1.0 was completed by Philippe Altherr, Vincent Cremet, Gilles Dubo-chet, Burak Emir, Stéphane Micheloud, Nikolay Mihaylov, Michel Schinz, Erik Sten- man, Matthias Zenger, and the author. Iulian Dragos, Gilles Dubochet, PhilippHaller, Sean McDirmid, Lex Spoon, and Geoffrey Washburn joined in the effort todevelop the second version of the language and tools. Gilad Bracha, Craig Cham- bers, Erik Ernst, Matthias Felleisen, Shriram Krishnamurti, Gary Leavens, SebastianManeth, Erik Meijer, Klaus Ostermann, Didier Rémy, Mads Torgersen, and PhilipWadler have shaped the design of the language through lively and inspiring discus- sions and comments on previous versions of this document. The contributors tothe Scala mailing list have also given very useful feedback that helped us improvethe language and its tools. --------------------------------------------------------------------------------------------------------------------------------------------------------------Chapter 1Lexical Syntax Scala programs are written using the Unicode Basic Multilingual Plane (BMP) char-acter set; Unicode supplementary characters are not presently supported. Thischapter defines the two modes of Scala's lexical syntax, the Scala mode and the XML mode. If not otherwise mentioned, the following descriptions of Scala tokens referto Scala mode, and literal characters `c' refer to the ASCII fragment \u0000-\u007F.In Scala mode, Unicode escapes are replaced by the corresponding Unicode charac- ter with the given hexadecimal code.UnicodeEscape ::= \{\\}u{u} hexDigit hexDigit hexDigit hexDigithexDigit::= `0' | · · · | `9' | `A' | · · · | `F' | `a' | · · · | `f' | To construct tokens, characters are distinguished according to the following classes(Unicode general category given in parentheses) :1. Whitespace characters. \u0020 | \u0009 | \u000D | \u000A 2. Letters, which include lower case letters(Ll) , upper case letters(Lu) , title-case letters(Lt) , other letters(Lo) , letter numerals(Nl) and the two characters\u0024 `$' and \u005F `', which both count as upper case letters 3. Digits `0' | . . . | `9'.4. Parentheses `(' | `) ' | `[' | `]' | `{' | `}'.5. Delimiter characters ``' | `'' | `"' | `.' | `;' | `,'. 6. Operator characters.These consist of all printable ASCII characters\u0020-\u007F. which are in none of the sets above, mathematical sym-bols(Sm) and other symbols(So) . ------------------------------------------------------------------------------- 4Lexical Syntax  1.1
IdentifiersSyntax:op::=opchar {opchar}varid::=lower idrestplainid ::=upper idrest|varid|opid::=plainid|`\`' stringLit `\`'idrest::= {letter | digit} [`' op]
There are three ways to form an identifier. First, an identifier can start witha letter which can be followed by an arbitrary sequence of letters and digits. This may be followed by underscore `' characters and another string composed ofeither letters and digits or of operator characters. Second, an identifier canstart with an operator character followed by an arbitrary sequence of operator characters. The preceding two forms are called plain identifiers. Finally, anidentifier may also be formed by an arbitrary string between back-quotes (hostsystems may impose some restrictions on which strings are legal for identifiers.)
The identifier then is composed of all characters excluding the backquotesthemselves. As usual, a longest match rule applies. For instance, the stringbigbob++=`def` decomposes into the three identifiers bigbob, ++=, and def. The rules for pattern matching further distinguish between variable identifiers,which start with a lower case letter, and constant identifiers, which do not.The `$' character is reserved for compiler-synthesized identifiers. User programs should not define identifiers which contain `$' characters. Thefollowing names are reserved words instead of being members of the syntacticclass id of lexical identifiers.
  abstract case catch class def do else extends false final finally for  forSome if implicit import lazy match new null object override package  private protected return sealed super this throw trait try true type val   var while with yield _ : = => <- <: <% >: # @
The Unicode operators \u21D2 `' and \u2190 `', which have the ASCII equiva-------------------------------------------------------------------------------- 1.2 Newline Characters5lents `=>' and `<-', are also reserved.Example 1.1.1 Here are examples of identifiers:xObjectmaxIndex p2p empty?+`yield`
ydotproduct*_systemMAXLEN_Example 1.1.2 Backquote-enclosed strings are a solution when one needs to ac- cess Java identifiers that are reserved words in Scala. For instance, the statementThread.yield() is illegal, since yield is a reserved word in Scala. However, here's awork-around:Thread.`yield`() 1.2Newline CharactersSyntax:semi ::= `;' |nl {nl}Scala is a line-oriented language where statements may be terminated by semi-colons or newlines. A newline in a Scala source text is treated as the special token "nl" if the three following criteria are satisfied:1. The token immediately preceding the newline can terminate a statement.2. The token immediately following the newline can begin a statement. 3. The token appears in a region where newlines are enabled.The tokens that can terminate a statement are: literals, identifiers and the followingdelimiters and reserved words:
  this null true false return type <xml-start> _ ) ] }
The tokens that can begin a statement are all Scala tokens except the following de-limiters and reserved words:
  catch else extends finally forSome match with yield , . ; : = => <- <:  <% >: # [ ) ] }
A case token can begin a statement only if followed by a class or object token. Newlines are enabled in:-------------------------------------------------------------------------------6Lexical Syntax1. all of a Scala source file, except for nested regions where newlines are disabled, and2. the interval between matching { and } brace tokens, except for nested regionswhere newlines are disabled.Newlines are disabled in:1. the interval between matching ( and ) parenthesis tokens, except for nested regions where newlines are enabled, and2. the interval between matching [ and ] bracket tokens, except for nested re-gions where newlines are enabled.3. The interval between a case token and its matching => token, except for nested regions where newlines are enabled.4. Any regions analyzed in XML mode (§1.5) .Note that the brace characters of {...} escapes in XML and string literals are nottokens, and therefore do not enclose a region where newlines are enabled. Normally, only a single nl token is inserted between two consecutive non-newlinetokens which are on different lines, even if there are multiple lines between the twotokens. However, if two tokens are separated by at least one completely blank line (i.e a line which contains no printable characters) , then two nl tokens are inserted.The Scala grammar (given in full in Appendix A) contains productions where op-tional nl tokens, but not semicolons, are accepted. This has the effect that a new- line in one of these positions does not terminate an expression or statement. Thesepositions can be summarized as follows:Multiple newline tokens are accepted in the following places (note that a semicolon in place of the newline would be illegal in every one of these cases) :­ between the condition of an conditional expression (§6.16) or while loop(§6.17) and the next following expression, ­ between the enumerators of a for-comprehension (§6.19) and the next follow-ing expression, and­ after the initial type keyword in a type definition or declaration (§4.3) .A single new line token is accepted ­ in front of an opening brace "{", if that brace is a legal continuation of thecurrent statement or expression,­ after an infix operator, if the first token on the next line can start an expression (§6.12) ,-------------------------------------------------------------------------------1.2 Newline Characters7­ in front of a parameter clause (§4.6) ,and­ after an annotation (§11) . Example 1.2.1 The following code contains four well-formed statements, each ontwo lines. The newline tokens between the two lines are not treated as statementseparators.if (x > 0) x = x - 1while (x > 0)x= x / 2for (x <- 1 to 10)println(x)typeIntList = List[Int]Example 1.2.2 The following code designates an anonymous class new Iterator[Int]{private var x = 0def hasNext = truedef next = { x += 1; x }}With an additional newline character, the same code is interpreted as an object cre- ation followed by a local block:new Iterator[Int]{private var x = 0def hasNext = truedef next = { x += 1; x }}Example 1.2.3 The following code designates a single expression: x < 0 ||x > 10With an additional newline character, the same code is interpreted as two expres-sions:------------------------------------------------------------------------------- 8Lexical Syntaxx < 0 ||x > 10Example 1.2.4 The following code designates a single, curried function definition:def func(x: Int)(y: Int) = x + y With an additional newline character, the same code is interpreted as an abstractfunction definition and a syntactically illegal statement:def func(x: Int)(y: Int) = x + y Example 1.2.5 The following code designates an attributed definition: @serializableprotected class Data { ... }With an additional newline character, the same code is interpreted as an attributeand a separate statement (which is syntactically illegal) . @serializableprotected class Data { ... }1.3LiteralsThere are literals for integer numbers, floating point numbers, characters, booleans,symbols, strings. The syntax of these literals is in each case as in Java. Syntax:Literal::=[`-'] integerLiteral|[`-'] floatingPointLiteral|booleanLiteral|characterLiteral| stringLiteral|symbolLiteral|`null'-------------------------------------------------------------------------------1.3 Literals9 1.3.1 Integer LiteralsSyntax:integerLiteral::=(decimalNumeral | hexNumeral | octalNumeral) [`L' | `l']decimalNumeral::=`0' | nonZeroDigit {digit} hexNumeral::=`0' `x' hexDigit {hexDigit}octalNumeral::=`0' octalDigit {octalDigit}digit::=`0' | nonZeroDigit nonZeroDigit::=`1' | · · · | `9'octalDigit::=`0' | · · · | `7'Integer literals are usually of type Int, or of type Long when followed by a L or l suffix. Values of type Int are all integer numbers between -231 and 231 - 1, inclu-sive. Values of type Long are all integer numbers between -263 and 263 -1, inclusive.A compile-time error occurs if an integer literal denotes a number outside these ranges.However, if the expected type pt (§6.1) of a literal in an expression is either Byte,Short, or Char and the integer number fits in the numeric range defined by the type,then the number is converted to type pt and the literal's type is pt. The numeric ranges given by these types are:Byte-27 to 27 - 1Short-215 to 215 - 1Char0 to 216 - 1Example 1.3.1 Here are some integer literals: 0210xFFFFFFFF0777L1.3.2 Floating Point LiteralsSyntax:floatingPointLiteral::=digit {digit} `.' {digit} [exponentPart] [floatType] |`.' digit {digit} [exponentPart] [floatType]|digit {digit} exponentPart [floatType]|digit {digit} [exponentPart] floatTypeexponentPart ::=(`E' | `e') [`+' | `-'] digit {digit}floatType::=`F' | `f' | `D' | `d'Floating point literals are of type Float when followed by a floating point type suffix F or f, and are of type Double otherwise. The type Float consists of all IEEE 754 32-bit single-precision binary floating point values, whereas the type Double consistsof all IEEE 754 64-bit double-precision binary floating point values. -------------------------------------------------------------------------------10Lexical SyntaxIf a floating point literal in a program is followed by a token starting with a letter, there must be at least one intervening whitespace character between the two to-kens.Example 1.3.2 Here are some floating point literals:0.01e30f3.14159f 1.0e-100.1Example 1.3.3 The phrase `1.toString' parses as three different tokens: `1', `.',and `toString'. On the other hand, if a space is inserted after the period, the phrase `1. toString' parses as the floating point literal `1.' followed by the iden-tifier `toString'.1.3.3 Boolean LiteralsSyntax:booleanLiteral::= `true' | `false'The boolean literals true and false are members of type Boolean.1.3.4 Character LiteralsSyntax:characterLiteral::=`\'' printableChar `\'' |`\'' charEscapeSeq `\''A character literal is a single character enclosed in quotes. The character is either aprintable unicode character or is described by an escape sequence (§1.3.6) . Example 1.3.4 Here are some character literals:'a''\u0041''\n''\t'Note that `\u000A' is not a valid character literal because Unicode conversion is done before literal parsing and the Unicode character \u000A (line feed) is not a printablecharacter. One can use instead the escape sequence `\n' or the octal escape `\12'(§1.3.6) . 1.3.5 String LiteralsSyntax:stringLiteral::=`\"' {stringElement} `\"'stringElement::=printableCharNoDoubleQuote| charEscapeSeq-------------------------------------------------------------------------------1.3 Literals11A string literal is a sequence of characters in double quotes. The characters are ei- ther printable unicode character or are described by escape sequences (§1.3.6) .Ifthe string literal contains a double quote character, it must be escaped, i.e. \". Thevalue of a string literal is an instance of class String. Example 1.3.5 Here are some string literals:"Hello,\nWorld!""This string contains a \" character."Multi-Line String LiteralsSyntax:stringLiteral ::=`"""' multiLineChars `"""'multiLineChars::={['"'] ['"'] charNoDoubleQuote} {`"'}A multi-line string literal is a sequence of characters enclosed in triple quotes """ ... """. The sequence of characters is arbitrary, except that it may containthree or more consuctive quote characters only at the very end. Characters mustnot necessarily be printable; newlines or other control characters are also permit- ted. Unicode escapes work as everywhere else, but none of the escape sequences in(§1.3.6) is interpreted.Example 1.3.6 Here is a multi-line string literal:"""the present string spans threelines."""This would produce the string:the present stringspans threelines.The Scala library contains a utility method stripMargin which can be used to strip leading whitespace from multi-line strings. The expression"""the present string|spans three|lines.""".stripMarginevaluates tothe present string -------------------------------------------------------------------------------12Lexical Syntaxspans threelines.Method stripMargin is defined in class scala.collection.immutable.StringLike. Because there is a predefined implicit conversion (§6.26) from String toStringLike, the method is applicable to all strings.1.3.6 Escape SequencesThe following escape sequences are recognized in character and string literals.     \b    \u0008: backspace BS    \t    \u0009: horizontal tab HT    \n    \u000a: linefeed LF    \f    \u000c: form feed FF    \r     \u000d: carriage return CR    \"    \u0022: double quote "    \'    \u0027: single quote '    \\    \u005c: backslash \ A character with Unicode between 0 and 255 may also be represented by an octalescape, i.e. a backslash `\' followed by a sequence of up to three octal characters.It is a compile time error if a backslash character in a character or string literal does not start a valid escape sequence.1.3.7 Symbol literalsSyntax:symbolLiteral::=`'' plainidA symbol literal 'x is a shorthand for the expression scala.Symbol("x") . Symbol is a case class (§5.3.2) ,which is defined as follows.package scalafinal case class Symbol private (name: String) {override def toString: String = "'" + name } The apply method of Symbol's companion object caches weak references to Symbols,thus ensuring that identical symbol literals are equivalent with respect to referenceequality.------------------------------------------------------------------------------- 1.4 Whitespace and Comments131.4Whitespace and CommentsTokens may be separated by whitespace characters and/or comments. Commentscome in two forms:A single-line comment is a sequence of characters which starts with // and extends to the end of the line.A multi-line comment is a sequence of characters between /* and */. Multi-linecomments may be nested, but are required to be properly nested. Therefore, a com- ment like /* /* */ will be rejected as having an unterminated comment. 1.5XML modeIn order to allow literal inclusion of XML fragments, lexical analysis switches fromScala mode to XML mode when encountering an opening angle bracket '<' in the following circumstance: The '<' must be preceded either by whitespace, an openingparenthesis or an opening brace and immediately followed by a character startingan XML name. Syntax:( whitespace | `(' | `{' ) `<' (XNameStart | `!' | `?')XNameStart ::= `' | BaseChar | Ideographic (as in W3C XML, but without `:'The scanner switches from XML mode to Scala mode if either · the XML expression or the XML pattern started by the initial '<' has been suc-cessfully parsed, or if· the parser encounters an embedded Scala expression or pattern and forces the Scanner back to normal mode, until the Scala expression or pattern is suc-cessfully parsed. In this case, since code and XML fragments can be nested,the parser has to maintain a stack that reflects the nesting of XML and Scala expressions adequately.Note that no Scala tokens are constructed in XML mode, and that comments areinterpreted as text.Example 1.5.1 The following value definition uses an XML literal with two embed- ded Scala expressionsval b = <book><title>The Scala Language Specification</title><version>{scalaBook.version}</version><authors>{scalaBook.authors.mkList("", ", ", "") }</authors> </book>--------------------------------------------------------------------------------------------------------------------------------------------------------------Chapter 2 Identifiers, Names and ScopesNames in Scala identify types, values, methods, and classes which are collectivelycalled entities. Names are introduced by local definitions and declarations (§4) ,in- heritance (§5.1.3) ,import clauses (§4.7) ,or package clauses (§9.2) which are collec-tively called bindings.Bindings of different kinds have a precedence defined on them:1. Definitions and declarations that are local, inherited, or made available by a package clause in the same compilation unit where the definition occurs havehighest precedence.2. Explicit imports have next highest precedence.3. Wildcard imports have next highest precedence. 4. Definitions made available by a package clause not in the compilation unitwhere the definition occurs have lowest precedence.There are two different name spaces, one for types (§3) and one for terms (§6) .The same name may designate a type and a term, depending on the context where thename is used.A binding has a scope in which the entity defined by a single name can be accessedusing a simple name. Scopes are nested. A binding in some inner scope shadows bindings of lower precedence in the same scope as well as bindings of the same orlower precedence in outer scopes.Note that shadowing is only a partial order. In a situation likeval x = 1; { import p.x;x }-------------------------------------------------------------------------------16Identifiers, Names and Scopesneither binding of x shadows the other. Consequently, the reference to x in the third line above would be ambiguous.A reference to an unqualified (type- or term-) identifier x is bound by the uniquebinding, which· defines an entity with name x in the same namespace as the identifier, and · shadows all other bindings that define entities with name x in that names-pace.It is an error if no such binding exists. If x is bound by an import clause, then thesimple name x is taken to be equivalent to the qualified name to which x is mapped by the import clause. If x is bound by a definition or declaration, then x refers tothe entity introduced by that binding. In that case, the type of x is the type of thereferenced entity. Example 2.0.2 Assume the following two definitions of a objects named X in pack-ages P and Q.package P {object X { val x = 1; val y = 2 }}package Q {object X { val x = true; val y = "" } }The following program illustrates different kinds of bindings and precedences be-tween them.
    package P {      // `X' bound by package clause       import Console._      // `println' bound by wildcard import      object A {        println("L4: "+X)        // `X' refers to `P.X' here        object B {           import Q._          // `X' bound by wildcard import          println("L7: "+X)          // `X' refers to `Q.X' here          import X._           // `x' and `y' bound by wildcard import          println("L8: "+x)          // `x' refers to `Q.X.x' here          object C {            val x = 3             // `x' bound by local definition            println("L12: "+x)            // `x' refers to constant `3' here            { import Q.X._              // `x' and `y' bound by wildcard import               //              println("L14: "+x)              // reference to `x' is ambiguous here              import X.y              // `y' bound by explicit import               println("L16: "+y)              // `y' refers to `Q.X.y' here              -------------------------------------------------------------------------------               17              { val x = "abc"                // `x' bound by local definition                import P.X._                // `x' and `y' bound by wildcard import                 //                println("L19: "+y) // reference to `y' is ambiguous here                println("L20: "+x) // `x' refers to string ``abc'' here               }            }          }        }      }    }
A reference to a qualified (type- or term-) identifier e.x refers to the member of the type T of e which has the name x in the same namespace as the identifier. It isan error if T is not a value type (§3.2) .The type of e.x is the member type of thereferenced entity in T . --------------------------------------------------------------------------------------------------------------------------------------------------------------Chapter 3TypesSyntax: Type::=FunctionArgTypes `=>' Type|InfixType [ExistentialClause]FunctionArgTypes::= InfixType| `(' [ ParamType {`,' ParamType } ] `) ' ExistentialClause ::=`forSome' `{' ExistentialDcl {semi ExistentialDcl} `}'ExistentialDcl::=`type' TypeDcl|`val' ValDcl InfixType::=CompoundType {id [nl] CompoundType}CompoundType::=AnnotType {`with' AnnotType} [Refinement]|RefinementAnnotType ::=SimpleType {Annotation}SimpleType::=SimpleType TypeArgs|SimpleType `#' id|StableId|Path `.' `type' |`(' Types ') 'TypeArgs::=`[' Types `]'Types::=Type {`,' Type}We distinguish between first-order types and type constructors, which take type pa- rameters and yield types. A subset of first-order types called value types representssets of (first-class) values. Value types are either concrete or abstract.Every concrete value type can be represented as a class type, i.e. a type designator (§3.2.3) that refers to a a class or a trait1(§5.3) ,or as a compound type (§3.2.7) rep-resenting an intersection of types, possibly with a refinement (§3.2.7) that furtherconstrains the types of its members. Abstract value types are introduced by type 1We assume that objects and packages also implicitly define a class (of the same name as theobject or package, but inaccessible to user programs) .------------------------------------------------------------------------------- 20Typesparameters (§4.4) and abstract type bindings (§4.3) .Parentheses in types can beused for grouping.Non-value types capture properties of identifiers that are not values (§3.3) .For ex- ample, a type constructor (§3.3.3) does not directly specify a type of values. How-ever, when a type constructor is applied to the correct type arguments, it yields afirst-order type, which may be a value type. Non-value types are expressed indirectly in Scala. E.g., a method type is describedby writing down a method signature, which in itself is not a real type, although itgives rise to a corresponding method type (§3.3.1) .Type constructors are another example, as one can write type Swap[m[, ], a,b] = m[b, a], but there is nosyntax to write the corresponding anonymous type function directly.3.1PathsSyntax:Path ::=StableId|[id `.'] thisStableId::=id|Path `.' id|[id '.'] `super' [ClassQualifier] `.' id ClassQualifier::= `[' id `]'Paths are not types themselves, but they can be a part of named types and in thatfunction form a central role in Scala's type system. A path is one of the following.· The empty path (which cannot be written explicitly in user programs) .· C .this, where C references a class. The path this is taken as a shorthand forC .this where C is the name of the class directly enclosing the reference. · p.x where p is a path and x is a stable member of p. Stable members arepackages or members introduced by object definitions or by value definitionsof non-volatile types (§3.6) .· C .super.x or C .super[M ].x where C references a class and x references a stable member of the super class or designated parent class M of C . The prefixsuper is taken as a shorthand for C .super where C is the name of the classdirectly enclosing the reference. A stable identifier is a path which ends in an identifier.-------------------------------------------------------------------------------3.2 Value Types213.2Value Types Every value in Scala has a type which is of one of the following forms.3.2.1 Singleton TypesSyntax:SimpleType::=Path `.' typeA singleton type is of the form p.type, where p is a path pointing to a value expected to conform (§6.1) to scala.AnyRef. The type denotes the set of values consisting ofnull and the value denoted by p.A stable type is either a singleton type or a type which is declared to be a subtype of trait scala.Singleton.3.2.2 Type ProjectionSyntax:SimpleType::=SimpleType `#' idA type projection T #x references the type member named x of type T . 3.2.3 Type DesignatorsSyntax:SimpleType::=StableIdA type designator refers to a named value type. It can be simple or qualified. Allsuch type designators are shorthands for type projections. Specifically, the unqualified type name t where t is bound in some class, object, orpackage C is taken as a shorthand for C .this.type#t . If t is not bound in a class,object, or package, then t is taken as a shorthand for .type#t . A qualified type designator has the form p.t where p is a path (§3.1) and t is a typename. Such a type designator is equivalent to the type projection p.type#t .Example 3.2.1 Some type designators and their expansions are listed below. We assume a local type parameter t , a value maintable with a type member Node andthe standard class scala.Int,t.type#tIntscala.type#Intscala.Int scala.type#Intdata.maintable.Nodedata.maintable.type#Node-------------------------------------------------------------------------------22Types3.2.4 Parameterized Types Syntax:SimpleType::=SimpleType TypeArgsTypeArgs::=`[' Types `]'A parameterized type T [U1, ..., Un] consists of a type designator T and type param- eters U1, ..., Un where n 1. T must refer to a type constructor which takes n typeparameters a1, ..., an.Say the type parameters have lower bounds L1, ..., Ln and upper bounds U1, ..., Un. The parameterized type is well-formed if each actual type parameter conforms to itsbounds, i.e. Li <: Ti <: Ui where is the substitution [a1 := T1, ..., an := Tn].Example 3.2.2 Given the partial type definitions:
    class TreeMap[A <: Comparable[A], B] { . . . }    class List[A] { . . . }    class I extends Comparable[I] { . . . }    class F[M[], X] { . . . }    class S[K <: String] { . . . }     class G[M[ Z <: I ], I] { . . . }
the following parameterized types are well formed:
    TreeMap[I, String]    List[I]    List[List[Boolean]]     F[List, Int]    G[S, String]
Example 3.2.3 Given the type definitions of Example 3.2.2,the following types areill-formed:TreeMap[I]// illegal: wrong number of parameters TreeMap[List[I], Int] // illegal: type parameter not within boundF[Int, Boolean]// illegal: Int is not a type constructorF[TreeMap, Int]// illegal: TreeMap takes two parameters, //F expects a constructor taking oneG[S, Int]// illegal: S constrains its parameter to//conform to String,// G expects type constructor with a parameter //that conforms to Int-------------------------------------------------------------------------------3.2 Value Types233.2.5 Tuple TypesSyntax: SimpleType::=`(' Types ') 'A tuple type (T1, ..., Tn) is an alias for the class scala.Tuplen[T1, ..., Tn], wheren 2.Tuple classes are case classes whose fields can be accessed using selectors 1, ..., n. Their functionality is abstracted in a corresponding Product trait. The n-ary tupleclass and product trait are defined at least as follows in the standard Scala library(they might also add other methods and implement other traits) . case class Tuplen[+T1, ..., +Tn](1: T1, ..., n: Tn)extends Productn[T1, ..., Tn] {}trait Productn[+T1, +T2, +Tn] {override def productArity = ndef 1: T1... def n:Tn}3.2.6 Annotated TypesSyntax:AnnotType::=SimpleType {Annotation}An annotated type T a1 ... an attaches annotations a1, ..., an to the type T (§11) . Example 3.2.4 The following type adds the @suspendable@ annotation to the typeString:String @suspendable3.2.7 Compound TypesSyntax:CompoundType::= AnnotType {`with' AnnotType} [Refinement]|RefinementRefinement::=[nl] `{' RefineStat {semi RefineStat} `}'RefineStat::= Dcl|`type' TypeDef|-------------------------------------------------------------------------------24TypesA compound type T1 with ... with Tn {R } represents objects with members as given in the component types T1, ..., Tn and the refinement {R }. A refinement {R }contains declarations and type definitions. If a declaration or definition overrides adeclaration or definition in one of the component types T1, ..., Tn, the usual rules for overriding (§5.1.4) apply; otherwise the declaration or definition is said to be"structural"2.Within a method declaration in a structural refinement, the type of any value pa- rameter may only refer to type parameters or abstract types that are contained in-side the refinement. That is, it must refer either to a type parameter of the methoditself, or to a type definition within the refinement. This restriction does not apply to the function's result type.If no refinement is given, the empty refinement is implicitly added, i.e.T1 with ... with Tn is a shorthand for T1 with ... with Tn {}.A compound type may also consist of just a refinement {R } with no preceding component types. Such a type is equivalent to AnyRef{R }.Example 3.2.5 The following example shows how to declare and use a functionwhich parameter's type contains a refinement with structural declarations. case class Bird (val name: String) extends Object {def fly(height: Int) = ......}case class Plane (val callsign: String) extends Object {def fly(height: Int) = ... ...}def takeoff(runway: Int,r: { val callsign: String; def fly(height: Int) }) = {tower.print(r.callsign + " requests take-off on runway " + runway) tower.read(r.callsign + " is clear for take-off")r.fly(1000)}val bird = new Bird("Polly the parrot") { val callsign = name }val a380 = new Plane("TZ-987") takeoff(42, bird)takeoff(89, a380)Although Bird and Plane do not share any parent class other than Object, theparameter r of function takeoff is defined using a refinement with structural dec- larations to accept any object that declares a value callsign and a fly function.2A reference to a structurally defined member (method call or access to a value or variable) maygenerate binary code that is significantly slower than an equivalent code to a non-structural member. -------------------------------------------------------------------------------3.2 Value Types253.2.8 Infix TypesSyntax:InfixType::=CompoundType {id [nl] CompoundType} An infix type T1 op T2 consists of an infix operator op which gets applied to twotype operands T1 and T2. The type is equivalent to the type application op[T1,T2].The infix operator op may be an arbitrary identifier, except for *, which is reserved as a postfix modifier denoting a repeated parameter type (§4.6.2) .All type infix operators have the same precedence; parentheses have to be used forgrouping. The associativity (§6.12) of a type operator is determined as for term op- erators: type operators ending in a colon `:' are right-associative; all other operatorsare left-associative.In a sequence of consecutive type infix operations t0 op1 t1 op2 ...opn tn, all opera- tors op1, ..., opn must have the same associativity. If they are all left-associative, thesequence is interpreted as (. . . (t0 op1 t1) op2 ...) opn tn, otherwise it is interpreted ast0 op1 (t1 op2 (...opn tn) ...) . 3.2.9 Function TypesSyntax:Type::=FunctionArgs `=>' TypeFunctionArgs::=InfixType|`(' [ ParamType {`,' ParamType } ] `) ' The type (T1, ..., Tn) => U represents the set of function values that take argu-ments of types T1, ..., Tn and yield results of type U . In the case of exactly oneargument type T => U is a shorthand for (T ) => U . An argument type of the form => T represents a call-by-name parameter (§4.6.1) of type T .Function types associate to the right, e.g.S => T => Uis the same asS => (T => U ) . Function types are shorthands for class types that define apply functions. Specif-ically, the n-ary function type (T1, ..., Tn) => U is a shorthand for the class typeFunctionn[T1, . . . , Tn,U ]. Such class types are defined in the Scala library for n between 0 and 9 as follows.package scalatrait Functionn[-T1, . . . , -Tn, +R] {def apply(x1: T1, . . . , xn: Tn) : Roverride def toString = "<function>" }Hence, function types are covariant (§4.5) in their result type and contravariant in-------------------------------------------------------------------------------26Types their argument types.3.2.10 Existential TypesSyntax:Type::= InfixType ExistentialClausesExistentialClauses ::= `forSome' `{' ExistentialDcl{semi ExistentialDcl} `}' ExistentialDcl::= `type' TypeDcl|`val' ValDclAn existential type has the form T forSome {Q } where Q is a sequence of typedeclarations §4.3.Let t1[tps1] >: L1 <: U1, ..., tn[tpsn] >: Ln <: Un be the types de- clared in Q (any of the type parameter sections [tpsi ] might be missing) . The scopeof each type ti includes the type T and the existential clause Q. The type variablesti are said to be bound in the type T forSome {Q }. Type variables which occur in a type T but which are not bound in T are said to be free in T .A type instance of T forSome {Q } is a type T where is a substitution overt1, ..., tn such that, for each i , Li <: ti <: Ui . The set of values denoted by the existential type T forSome {Q } is the union of the set of values of all its type in-stances.A skolemization of T forSome {Q } is a type instance T , where is the substitu-tion [t /t is a fresh abstract type with lower bound L11, . . . , tn /tn ] and each tii andupper bound Ui .Simplification RulesExistential types obey the following four equivalences: 1. Multiple for-clauses in an existential type can be merged.E.g.,T forSome {Q } forSome {Q } is equivalent to T forSome {Q ;Q }.2. Unused quantifications can be dropped. E.g., T forSome {Q ;Q } where none of the types defined in Q are referred to by T or Q, is equivalent toT forSome {Q }.3. An empty quantification can be dropped. E.g., T forSome { } is equivalentto T . 4. An existential type T forSome {Q }where Q contains a clausetype t [tps] >: L <: U is equivalent to the typeT forSome {Q }whereT results from T by replacing every covariant occurrence (§4.5) of t in T by U and by replacing every contravariant occurrence of t in T by L.-------------------------------------------------------------------------------3.2 Value Types27Existential Quantification over Values As a syntactic convenience,the bindings clause in an existential typemayalsocontainvaluedeclarationsval x: T .Anexistential typeT forSome { Q; val x: S ;Q }is treated as a shorthand for the typeT forSome { Q; type t <: S with Singleton; Q }, where t is a fresh typename and T results from T by replacing every occurrence of x.type with t . Placeholder Syntax for Existential TypesSyntax:WildcardType::=`' TypeBoundsScala supports a placeholder syntax for existential types. A wildcard type is of the form _ >: L <:U . Both bound clauses may be omitted. If a lower bound clause >: Lis missing, >: scala.Nothing is assumed. If an upper bound clause <:U is miss-ing, <: scala.Any is assumed. A wildcard type is a shorthand for an existentially quantified type variable, where the existential quantification is implicit.A wildcard type must appear as type argument of a parameterized type. Let T =p.c[targs, T, targs ] be a parameterized type where targs, targs may be empty and T is a wildcard type _ >: L <:U . Then T is equivalent to the existential typep.c[targs, t , targs ] forSome { type t >: L <: U }where t is some fresh type variable. Wildcard types may also appear as parts of infix types (§3.2.8) ,function types (§3.2.9) ,or tuple types (§3.2.5) .Their expansion isthen the expansion in the equivalent parameterized type.Example 3.2.6 Assume the class definitions class Ref[T] abstract class Outer { type T } .Here are some examples of existential types:Ref[T] forSome { type T <: java.lang.Number }Ref[x.T] forSome { val x: Outer }Ref[xtype # T] forSome { type xtype <: Outer with Singleton } The last two types in this list are equivalent. An alternative formulation of the firsttype above using wildcard syntax is:Ref[_ <: java.lang.Number]Example 3.2.7 The type List[List[]] is equivalent to the existential type -------------------------------------------------------------------------------28TypesList[List[t] forSome { type t }] .Example 3.2.8 Assume a covariant typeclass List[+T] The typeList[T] forSome { type T <: java.lang.Number }is equivalent (by simplification rule 4 above) toList[java.lang.Number] forSome { type T <: java.lang.Number }which is in turn equivalent (by simplification rules 2 and 3 above) to List[java.lang.Number].3.3Non-Value TypesThe types explained in the following do not denote sets of values, nor do they appearexplicitly in programs. They are introduced in this report as the internal types of defined identifiers.3.3.1 Method TypesA method type is denoted internally as (Ps) U , where (Ps) is a sequence of parameternames and types (p1 : T1, ..., pn : Tn) for some n 0 and U is a (value or method) type. This type represents named methods that take arguments named p1, ..., pnof types T1, ..., Tn and that return a result of type U .Method types associate to the right: (Ps1) (Ps2) U is treated as (Ps1) ((Ps2) U ) . A special case are types of methods without any parameters. They are written here=> T. Parameterless methods name expressions that are re-evaluated each time theparameterless method name is referenced. Method types do not exist as types of values. If a method name is used as a value, itstype is implicitly converted to a corresponding function type (§6.26) .Example 3.3.1 The declarations def a: Intdef b (x: Int) : Booleandef c (x: Int) (y: String, z: String) : Stringproduce the typings------------------------------------------------------------------------------- 3.4 Base Types and Member Definitions29a: => Intb: (Int) Booleanc: (Int) (String, String) String3.3.2 Polymorphic Method TypesA polymorphic method type is denoted internally as [tps ]T where [tps ] is a type parameter section [a1 >: L1 <: U1, ..., an >: Ln <: Un] for some n 0 and Tis a (value or method) type. This type represents named methods that take typearguments S1, ..., Sn which conform (§3.2.4) to the lower bounds L1, ..., Ln and the upper bounds U1, ..., Un and that yield results of type T .Example 3.3.2 The declarationsdef empty[A]: List[A]def union[A <: Comparable[A]] (x: Set[A], xs: Set[A]) : Set[A] produce the typingsempty : [A >: Nothing <: Any] List[A]union : [A >: Nothing <: Comparable[A]] (x: Set[A], xs: Set[A]) Set[A].3.3.3 Type Constructors A type constructor is represented internally much like a polymorphic method type.[± a1 >: L1 <: U1, . . . , ±an >: Ln <: Un] T represents a type that is expectedby a type constructor parameter (§4.4) or an abstract type constructor binding (§4.3) with the corresponding type parameter clause.Example 3.3.3 Consider this fragment of the Iterable[+X] class:trait Iterable[+X] {def flatMap[newType[+X] <: Iterable[X], S](f: X => newType[S]) : newType[S] }Conceptually, the type constructor Iterable is a name for the anonymous type[+X] Iterable[X], which may be passed to the newType type constructor param-eter in flatMap.3.4 Base Types and Member DefinitionsTypes of class members depend on the way the members are referenced. Centralhere are three notions, namely:------------------------------------------------------------------------------- 30Types1. the notion of the set of base types of a type T ,2. the notion of a type T in some class C seen from some prefix type S,3. the notion of the set of member bindings of some type T . These notions are defined mutually recursively as follows.1. The set of base types of a type is a set of class types, given as follows.· The base types of a class type C with parents T1, ..., Tn are C itself, as well as the base types of the compound type T1 with ... with Tn {R }.· The base types of an aliased type are the base types of its alias.· The base types of an abstract type are the base types of its upper bound. · The base types of a parameterized type C [T1, ..., Tn] are the base types oftype C , where every occurrence of a type parameter ai of C has been replacedby the corresponding parameter type Ti . · The base types of a singleton type p.type are the base types of the type of p.· The base types of a compound type T1 with ... with Tn {R } are the re-duced union of the base classes of all Ti 's. This means: Let the multi-set S be the multi-set-union of the base types of all Ti 's. If S contains several typeinstances of the same class, say Si #C [T i , . . . , T i1n ] (i I ) , then all those in- stances are replaced by one of them which conforms to all others. It is anerror if no such instance exists. It follows that the reduced union, if it exists,produces a set of class types, where different types are instances of different classes.· The base types of a type selection S#T are determined as follows. If T is analias or abstract type, the previous clauses apply. Otherwise, T must be a (pos-sibly parameterized) class type, which is defined in some class B . Then the base types of S#T are the base types of T in B seen from the prefix type S.· The base types of an existential type T forSome {Q } are all typesS forSome {Q } where S is a base type of T . 2. The notion of a type T in class C seen from some prefix type S makes sense only ifthe prefix type S has a type instance of class C as a base type, say S #C [T1, ..., Tn].Then we define as follows. · If S =.type, then T in C seen from S is T itself.· Otherwise, if S is an existential type S forSome {Q }, and T in C seen fromS is T , then T in C seen from S is T forSome {Q }. · Otherwise, if T is the i 'th type parameter of some class D, then­ If S has a base typeD[U1, ..., Un], for some type parameters[U1, . . . , Un], then T in C seen from S is Ui . -------------------------------------------------------------------------------3.5 Relations between types31­ Otherwise, if C is defined in a class C , then T in C seen from S is the same as T in C seen from S .­ Otherwise, if C is not defined in another class, then T in C seen from S isT itself.· Otherwise, if T is the singleton type D.this.type for some class D then ­ If D is a subclass of C and S has a type instance of class D among its basetypes, then T in C seen from S is S.­ Otherwise, if C is defined in a class C , then T in C seen from S is the same as T in C seen from S .­ Otherwise, if C is not defined in another class, then T in C seen from S isT itself.· If T is some other type, then the described mapping is performed to all its type components.If T is a possibly parameterized class type, where T 's class is defined in some otherclass D, and S is some prefix type, then we use "T seen from S" as a shorthand for "T in D seen from S".3. The member bindings of a type T are (1) all bindings d such that there exists a typeinstance of some class C among the base types of T and there exists a definition or declaration d in C such that d results from d by replacing every type T in d by Tin C seen from T , and (2) all bindings of the type's refinement (§3.2.7) ,if it has one.The definition of a type projection S#t is the member binding dt of the type t in S. In that case, we also say that S#t is defined by dt . share a to3.5Relations between typesWe define two relations between types.Type equivalenceT UT and U are interchangeable in all contexts. ConformanceT <: UType T conforms to type U .3.5.1 Type EquivalenceEquivalence () between types is the smallest congruence3such that the followingholds: · If t is defined by a type alias type t = T , then t is equivalent to T .· If a path p has a singleton type q.type, then p.type  q.type.3 A congruence is an equivalence relation which is closed under formation of contexts -------------------------------------------------------------------------------32Types· If O is defined by an object definition, and p is a path consisting only of pack-age or object selectors and ending in O, then O.this.type  p.type. · Two compound types (§3.2.7) are equivalent if the sequences of their compo-nent are pairwise equivalent, and occur in the same order, and their refine-ments are equivalent. Two refinements are equivalent if they bind the same names and the modifiers, types and bounds of every declared entity are equiv-alent in both refinements.· Two method types (§3.3.1) are equivalent if they have equivalent result types, both have the same number of parameters, and corresponding parametershave equivalent types. Note that the names of parameters do not matter formethod type equivalence.· Two polymorphic method types (§3.3.2) are equivalent if they have the same number of type parameters, and, after renaming one set of type parameters byanother, the result types as well as lower and upper bounds of correspondingtype parameters are equivalent. · Two existential types (§3.2.10) are equivalent if they have the same numberof quantifiers, and, after renaming one list of type quantifiers by another, thequantified types as well as lower and upper bounds of corresponding quanti- fiers are equivalent.· Two type constructors (§3.3.3) are equivalent if they have the same number oftype parameters, and, after renaming one list of type parameters by another,the result types as well as variances, lower and upper bounds of correspond- ing type parameters are equivalent.3.5.2 ConformanceThe conformance relation (<:) is the smallest transitive relation that satisfies thefollowing conditions.· Conformance includes equivalence. If T U then T <: U . · For every value type T , scala.Nothing <: T <: scala.Any.· For every type constructor T (with any number of type parameters) ,scala.Nothing <: T <: scala.Any.· For every class type T such that T <: scala.AnyRef and not T <: scala.NotNull one has scala.Null <: T .· A type variable or abstract type t conforms to its upper bound and its lowerbound conforms to t .· A class type or parameterized type conforms to any of its base-types. · A singleton type p.type conforms to the type of the path p.· A singleton type p.type conforms to the type scala.Singleton.------------------------------------------------------------------------------- 3.5 Relations between types33· A type projection T #t conforms to U #t if T conforms to U .· A parameterized type T [T1, ..., Tn] conforms to T [U1, ..., Un] if the fol-lowing three conditions hold for i = 1, ..., n. ­ If the i 'th type parameter of T is declared covariant, then Ti <: Ui .­ If the i 'th type parameter of T is declared contravariant, then Ui <: Ti .­ If the i 'th type parameter of T is declared neither covariant nor con- travariant, then Ui  Ti .· A compound type T1 with ... with Tn {R } conforms to each of its compo-nent types Ti .· If T <: Ui for i = 1, ..., n and for every binding d of a type or value x in R there exists a member binding of x in T which subsumes d , then T conforms to thecompound type U1 with ... with Un {R }.· The existential type T forSome {Q } conforms to U if its skolemization (§3.2.10) conforms to U .· The type T conforms to the existential type U forSome {Q } if T conforms toone of the type instances (§3.2.10) of U forSome {Q }.· If Ti  T for ii = 1, . . . , n and U conforms to U then the method type (p1 :T1, ..., pn : Tn) U conforms to (p : T , ..., p11n : Tn ) U .· The polymorphic type [a1 >: L1 <: U1, ..., an >: Ln <: Un]T conforms to the polymorphic type [a1 >: L, . . . , a1 <: U1n >: Ln <: Un ]T if, assuming L1 <:a1 <: U , ..., Land U1n <: an <: Un one has T <: T and Li <: Lii <: Ui fori = 1, ..., n.· Type constructors T and T follow a similar discipline. We characterize Tand T by their type parameter clauses [a1, ..., an] and [a , ..., a 1n ], wherean ai or a may include a variance annotation, a higher-order type param-ieter clause, and bounds. Then, T conforms to T if any list [t1, ..., tn] ­with declared variances, bounds and higher-order type parameter clauses ­ of valid type arguments for T is also a valid list of type arguments for T andT [t1, ..., tn] <: T [t1, ..., tn]. Note that this entails that:­ The bounds on ai must be weaker than the corresponding bounds de- clared for a .i­ The variance of ai must match the variance of a , where covarianceimatches covariance, contravariance matches contravariance and anyvariance matches invariance. ­ Recursively, these restrictions apply to the corresponding higher-ordertype parameter clauses of ai and a .iA declaration or definition in some compound type of class type C subsumes an- other declaration of the same name in some compound type or class type C , if oneof the following holds.------------------------------------------------------------------------------- 34Types· A value declaration or definition that defines a name x with type T subsumesa value or method declaration that defines x with type T , provided T <: T .· A method declaration or definition that defines a name x with type T sub- sumes a method declaration that defines x with type T , provided T <: T .· A type alias type t [T1, ..., Tn] = T subsumes a type alias type t[T1, ..., Tn] = Tif T T .· A type declaration type t [T1, ..., Tn] >: L <: U subsumes a type declara- tion type t [T1, ..., Tn] >: L <: U if L <: L and U <: U .· A type or class definition that binds a type name t subsumes an abstract typedeclaration type t[T1, ..., Tn] >: L <: U if L <: t <: U . The (<:) relation forms pre-order between types, i.e. it is transitive and reflexive.least upper bounds and greatest lower bounds of a set of types are understood to berelative to that order. Note.The least upper bound or greatest lower bound of a set of types does notalways exist. For instance, consider the class definitionsclass A[+T] {}class B extends A[B] class C extends A[C]Then the types A[Any], A[A[Any]], A[A[A[Any]]], ... form a descending se-quence of upper bounds for B and C. The least upper bound would be the infinitelimit of that sequence, which does not exist as a Scala type. Since cases like this are in general impossible to detect, a Scala compiler is free to reject a term which hasa type specified as a least upper or greatest lower bound, and that bound would bemore complex than some compiler-set limit4. The least upper bound or greatest lower bound might also not be unique. For in-stance A with B and B with A are both greatest lower of A and B. If there are severalleast upper bounds or greatest lower bounds, the Scala compiler is free to pick any one of them.3.5.3 Weak ConformanceIn some situations Scala uses a more genral conformance relation. A type S weaklyconforms to a type T , written S <:w T , if S <: T or both S and T are primitive number types and S precedes T in the following ordering.Byte <:w ShortShort <:w Int4The current Scala compiler limits the nesting level of parameterization in such bounds to be at most two deeper than the maximum nesting level of the operand types-------------------------------------------------------------------------------3.6 Volatile Types35Char <:w Int Int <:w LongLong <:w FloatFloat <:w DoubleA weak least upper bound is a least upper bound with respect to weak conformance.3.6Volatile Types Type volatility approximates the possibility that a type parameter or abstract type instance of a type does not have any non-null values. As explained in (§3.1) ,a valuemember of a volatile type cannot appear in a path.A type is volatile if it falls into one of four categories: A compound type T1 with ... with Tn {R } is volatile if one of the following twoconditions hold.1. One of T2, ..., Tn is a type parameter or abstract type, or2. T1 is an abstract type and and either the refinement R or a type Tj for j > 1 contributes an abstract member to the compound type, or3. one of T1, ..., Tn is a singleton type.Here, a type S contributes an abstract member to a type T if S contains an abstractmember that is also a member of T . A refinement R contributes an abstract member to a type T if R contains an abstract declaration which is also a member of T .A type designator is volatile if it is an alias of a volatile type, or if it designates a typeparameter or abstract type that has a volatile type as its upper bound. A singleton type p.type is volatile, if the underlying type of path p is volatile.An existential type T forSome {Q } is volatile if T is volatile.3.7Type ErasureA type is called generic if it contains type arguments or type variables. Type erasure is a mapping from (possibly generic) types to non-generic types. We write |T | forthe erasure of type T . The erasure mapping is defined as follows.· The erasure of an alias type is the erasure of its right-hand side. · The erasure of an abstract type is the erasure of its upper bound.· The erasure of the parameterized type scala.Array[T1] is scala.Array[|T1|].· The erasure of every other parameterized type T [T1, ..., Tn] is |T |. -------------------------------------------------------------------------------36Types· The erasure of a singleton type p.type is the erasure of the type of p.· The erasure of a type projection T #x is |T |#x. · The erasure of a compound type T1 with ... with Tn {R } is the erasure ofthe intersection dominator of T1, ..., Tn.· The erasure of an existential type T forSome {Q } is |T |.The intersection dominator of a list of types T1, ..., Tn is computed as follows. Let Ti , ..., Tbe the subsequence of types T1imi which are not supertypes of some othertype T j . If this subsequence contains a type designator Tc that refers to a class which is not a trait, the intersection dominator is Tc. Otherwise, the intersection domina-tor is the first element of the subsequence, Ti .1------------------------------------------------------------------------------- Chapter 4Basic Declarations and DefinitionsSyntax:Dcl::=`val' ValDcl|`var' VarDcl|`def' FunDcl |`type' {nl} TypeDclPatVarDef::=`val' PatDef|`var' VarDefDef::=PatVarDef|`def' FunDef |`type' {nl} TypeDef|TmplDefA declaration introduces names and assigns them types. It can form part of a classdefinition (§5.1) or of a refinement in a compound type (§3.2.7) . A definition introduces names that denote terms or types. It can form part of anobject or class definition or it can be local to a block. Both declarations and defini-tions produce bindings that associate type names with type definitions or bounds, and that associate term names with types.The scope of a name introduced by a declaration or definition is the whole state-ment sequence containing the binding. However, there is a restriction on forward references in blocks: In a statement sequence s1 ... sn making up a block, if a simplename in si refers to an entity defined by s j where j i , then for all sk between andincluding si and s j , · sk cannot be a variable definition.· If sk is a value definition, it must be lazy.-------------------------------------------------------------------------------38Basic Declarations and Definitions 4.1Value Declarations and DefinitionsSyntax:Dcl::=`val' ValDclValDcl::=ids `:' TypePatVarDef::= `val' PatDefPatDef::=Pattern2 {`,' Pattern2} [`:' Type] `=' Exprids::=id {`,' id}A value declaration val x: T introduces x as a name of a value of type T . A value definition val x: T = e defines x as a name of the value that results fromthe evaluation of e. If the value definition is not recursive, the type T may be omit-ted, in which case the packed type (§6.1) of expression e is assumed. If a type T is given, then e is expected to conform to it.Evaluation of the value definition implies evaluation of its right-hand side e, unlessit has the modifier lazy. The effect of the value definition is to bind x to the value of e converted to type T . A lazy value definition evaluates its right hand side e thefirst time the value is accessed.A constant value definition is of the formfinal val x = e where e is a constant expression (§6.24) .The final modifier must be present andno type annotation may be given. References to the constant value x are themselvestreated as constant expressions; in the generated code they are replaced by the def- inition's right-hand side e.Value definitions can alternatively have a pattern (§8.1) as left-hand side. If p issome pattern other than a simple name or a name followed by a colon and a type, then the value definition val p = e is expanded as follows:1. If the pattern p has bound variables x1, ..., xn, where n > 1:val $x = e match {case p => (x1, . . . , xn) }val x1 = $x.1 . . .val xn = $x.n .Here, $x is a fresh name.2. If p has a unique bound variable x:val x = e match { case p => x }3. If p has no bound variables:e match { case p => () } -------------------------------------------------------------------------------4.2 Variable Declarations and Definitions39Example 4.1.1 The following are examples of value definitions     val pi = 3.1415    val pi: Double = 3.1415    // equivalent to first definition    val Some(x) = f()    // a pattern definition    val x :: xs = mylist     // an infix pattern definition    The last two definitions have the following expansions.    val x = f() match { case Some(x) => x }    val x$ = mylist match { case x :: xs => (x, xs) }     val x = x$.1    val xs = x$.2
The name of any declared or defined value may not end in =.A value declaration val x1, ..., xn: T is a shorthand for the sequence of value dec- larations val x1: T ; ...; val xn: T . A value definition val p1, ..., pn = e isa shorthand for the sequence of value definitions val p1 = e; ...; val pn = e.A value definition val p1, ..., pn : T = e is a shorthand for the sequence of value definitions val p1 : T = e; ...; val pn : T = e.4.2Variable Declarations and DefinitionsSyntax:Dcl::=`var' VarDclPatVarDef::= `var' VarDefVarDcl::=ids `:' TypeVarDef::=PatDef|ids `:' Type `=' `'A variable declaration var x: T is equivalent to declarations of a getter function x and a setter function x=, defined as follows:def x: Tdef x= (y: T ) : UnitAn implementation of a class containing variable declarations may define thesevariables using variable definitions, or it may define setter and getter functions di- rectly.A variable definition var x: T = e introduces a mutable variable with type T andinitial value as given by the expression e. The type T can be omitted, in which casethe type of e is assumed. If T is given, then e is expected to conform to it (§6.1) . Variable definitions can alternatively have a pattern (§8.1) as left-hand side. A vari--------------------------------------------------------------------------------40Basic Declarations and Definitions able definition var p = e where p is a pattern other than a simple name or a namefollowed by a colon and a type is expanded in the same way (§4.1) as a value defi-nition val p = e, except that the free names in p are introduced as mutable vari- ables, not values.The name of any declared or defined variable may not end in =.A variable definition var x: T = _ can appear only as a member of a template. Itintroduces a mutable field with type T and a default initial value. The default value depends on the type T as follows:0if T is Int or one of its subrange types,0Lif T is Long,0.0fif T is Float,0.0dif T is Double, falseif T is Boolean,()if T is Unit,nullfor all other types T .When they occur as members of a template, both forms of variable definition also introduce a getter function x which returns the value currently assigned to the vari-able, as well as a setter function x= which changes the value currently assigned tothe variable. The functions have the same signatures as for a variable declaration. The template then has these getter and setter functions as members, whereas theoriginal variable cannot be accessed directly as a template member.Example 4.2.1 The following example shows how properties can be simulated in Scala. It defines a class TimeOfDayVar of time values with updatable integer fieldsrepresenting hours, minutes, and seconds. Its implementation contains tests thatallow only legal values to be assigned to these fields. The user code, on the other hand, accesses these fields just like normal variables.
    class TimeOfDayVar {      private var h: Int = 0      private var m: Int = 0      private var s: Int = 0       def hours = h      def hours= (h: Int) =        if (0 <= h && h < 24) this.h = h        else throw new DateError()
      def minutes = m       def minutes= (m: Int) =        if (0 <= m && m < 60) this.m = m        else throw new DateError()
      def seconds = s      def seconds= (s: Int) =         if (0 <= s && s < 60) this.s = s        else throw new DateError()    }    val d = new TimeOfDayVar    d.hours = 8; d.minutes = 30; d.seconds = 0     d.hours = 25 // throws a DateError exception
A variable declarationvar x1, . . . , xn: Tis a shorthand for the se-quence of variable declarations var x1: T ; ...; var xn: T .A vari-able definitionvar x1, . . . , xn = eis a shorthand for the sequence ofvariable definitionsvar x1 = e; ...; var xn = e. A variable definitionvar x1, . . . , xn : T = eis a shorthand for the sequence of variable definitionsvar x1 : T = e; ...; var xn : T = e.4.3Type Declarations and Type Aliases Syntax:Dcl::=`type' {nl} TypeDclTypeDcl::=id [TypeParamClause] [`>:' Type] [`<:' Type]Def::=type {nl} TypeDef TypeDef::=id [TypeParamClause] `=' TypeA type declaration type t [tps ] >: L <: U declares t to be an abstract type withlower bound type L and upper bound type U . If the type parameter clause [tps ] is omitted, t abstracts over a first-order type, otherwise t stands for a type constructorthat accepts type arguments as described by the type parameter clause.If a type declaration appears as a member declaration of a type, implementations of the type may implement t with any type T for which L <: T <: U . It is a compile-time error if L does not conform to U . Either or both bounds may be omitted. If thelower bound L is absent, the bottom type scala.Nothing is assumed. If the upper bound U is absent, the top type scala.Any is assumed.A type constructor declaration imposes additional restrictions on the concrete typesfor which t may stand. Besides the bounds L and U , the type parameter clause may impose higher-order bounds and variances, as governed by the conformanceof type constructors (§3.5.2) .The scope of a type parameter extends over the bounds >: L <: U and the type parameter clause tps itself. A higher-order type parameter clause (of an abstracttype constructor t c) has the same kind of scope, restricted to the declaration of thetype parameter t c. Toillustratenestedscoping,thesedeclarationsareallequivalent:type t[m[x] <: Bound[x], Bound[x]],type t[m[x] <: Bound[x], Bound[y]] and type t[m[x] <: Bound[x], Bound[]], as the scope of, e.g., the type param--------------------------------------------------------------------------------42Basic Declarations and Definitions eter of m is limited to the declaration of m. In all of them, t is an abstract typemember that abstracts over two type constructors: m stands for a type constructorthat takes one type parameter and that must be a subtype of B ound , t 's second type constructor parameter. t[MutableList, Iterable] is a valid use of t .A type alias type t = T defines t to be an alias name for the type T . The left handside of a type alias may have a type parameter clause, e.g. type t [tps ] = T . The scope of a type parameter extends over the right hand side T and the type parameterclause tps itself.The scope rules for definitions (§4) and type parameters (§4.6) make it possible that a type name appears in its own bound or in its right-hand side. However, it is a staticerror if a type alias refers recursively to the defined type constructor itself. That is,the type T in a type alias type t [tps ] = T may not refer directly or indirectly to the name t . It is also an error if an abstract type is directly or indirectly its own upperor lower bound.Example 4.3.1 The following are legal type declarations and definitions:type IntList = List[Integer] type T <: Comparable[T]type Two[A] = Tuple2[A, A]type MyCollection[+X] <: Iterable[X]The following are illegal:type Abs = Comparable[Abs]// recursive type alias type S <: T// S, T are bounded by themselves.type T <: Stype T >: Comparable[T.That]// Cannot select from T.// T is a type, not a valuetype MyCollection <: Iterable // Type constructor members must explicitly state their type parameters.If a type alias type t [tps ] = S refers to a class type S, the name t can also be usedas a constructor for objects of type S. Example 4.3.2 The Predef object contains a definition which establishes Pair asan alias of the parameterized class Tuple2:type Pair[+A, +B] = Tuple2[A, B]object Pair {def apply[A, B](x: A, y: B) = Tuple2(x, y) def unapply[A, B](x: Tuple2[A, B]) : Option[Tuple2[A, B]] = Some(x)}-------------------------------------------------------------------------------4.4 Type Parameters43 As a consequence, for any two types S and T , the type Pair[S, T ] is equivalent tothe type Tuple2[S, T ]. Pair can also be used as a constructor instead of Tuple2,as in:val x: Pair[Int, String] = new Pair(1, "abc") 4.4Type ParametersSyntax:TypeParamClause::= `[' VariantTypeParam {`,' VariantTypeParam} `]'VariantTypeParam ::= {Annotation} [`+' | `-'] TypeParam TypeParam::= (id | `') [TypeParamClause] [`>:' Type] [`<:' Type] [`:' Type]Type parameters appear in type definitions, class definitions, and function defini-tions. In this section we consider only type parameter definitions with lower bounds >: L and upper bounds <: U whereas a discussion of context bounds : U andview bounds <% U is deferred to Section 7.4.Themostgeneralformof afirst-ordertypeparameteris@a1 ...@an ± t >: L <: U . Here, L, and U are lower and upper bounds thatconstrain possible type arguments for the parameter. It is a compile-time error if L does not conform to U . ± is a variance, i.e. an optional prefix of either +, or -. Oneor more annotations may precede the type parameter.The names of all type parameters must be pairwise different in their enclosing type parameter clause. The scope of a type parameter includes in each case the wholetype parameter clause. Therefore it is possible that a type parameter appears aspart of its own bounds or the bounds of other type parameters in the same clause. However, a type parameter may not be bounded directly or indirectly by itself.A type constructor parameter adds a nested type parameter clause to thetype parameter.The most general form of a type constructor parameter is @a1 ...@an ± t[tps] >: L <: U .The above scoping restrictions are generalized to the case of nested type parameterclauses, which declare higher-order type parameters. Higher-order type parame- ters (the type parameters of a type parameter t ) are only visible in their immediatelysurrounding parameter clause (possibly including clauses at a deeper nesting level)and in the bounds of t . Therefore, their names must only be pairwise different from the names of other visible parameters. Since the names of higher-order type pa-rameters are thus often irrelevant, they may be denoted with a `', which is nowherevisible.Example 4.4.1 Here are some well-formed type parameter clauses: [S, T]-------------------------------------------------------------------------------44Basic Declarations and Definitions[@specialized T, U][Ex <: Throwable] [A <: Comparable[B], B <: A][A, B >: A, C >: A <: B][M[X], N[X]][M[], N[]] // equivalent to previous clause[M[X <: Bound[X]], Bound[]][M[+X] <: Iterable[X]] The following type parameter clauses are illegal:[A >: A]// illegal, `A' has itself as bound[A <: B, B <: C, C <: A]// illegal, `A' has itself as bound [A, B, C >: A <: B]// illegal lower bound `A' of `C' does// not conform to upper bound `B'.4.5Variance AnnotationsVariance annotations indicate how instances of parameterized types vary with re- spect to subtyping (§3.5.2) .A `+' variance indicates a covariant dependency, a `-'variance indicates a contravariant dependency, and a missing variance indicationindicates an invariant dependency. A variance annotation constrains the way the annotated type variable may ap-pear in the type or class which binds the type parameter. In a type definitiontype T [tps ] = S, or a type declaration type T [tps ] >: L <: U type parameters labeled `+' must only appear in covariant position whereas type parameters labeled`-' must only appear in contravariant position. Analogously, for a class definitionclass C [tps ](ps ) extends T { x: S => ...}, type parameters labeled `+' must only appear in covariant position in the self type S and the template T , whereas typeparameters labeled `-' must only appear in contravariant position.The variance position of a type parameter in a type or template is defined as follows. Let the opposite of covariance be contravariance, and the opposite of invariance beitself. The top-level of the type or template is always in covariant position. Thevariance position changes at the following constructs. · The variance position of a method parameter is the opposite of the varianceposition of the enclosing parameter clause.· The variance position of a type parameter is the opposite of the variance po- sition of the enclosing type parameter clause.· The variance position of the lower bound of a type declaration or type param-eter is the opposite of the variance position of the type declaration or param- eter.-------------------------------------------------------------------------------4.5 Variance Annotations45· The type of a mutable variable is always in invariant position. · The prefix S of a type selection S#T is always in invariant position.· For a type argument T of a type S[. . . T . . . ]: If the corresponding type pa-rameter is invariant, then T is in invariant position. If the corresponding type parameter is contravariant, the variance position of T is the opposite of thevariance position of the enclosing type S[. . . T . . . ].References to the type parameters in object-private or object-protected values, vari- ables, or methods (§5.2) of the class are not checked for their variance position. Inthese members the type parameter may appear anywhere without restricting its le-gal variance annotations. Example 4.5.1 The following variance annotation is legal.abstract class P[+A, +B] {def fst: A; def snd: B}With this variance annotation, type instances of P subtype covariantly with respect to their arguments. For instance,P[IOException, String] <: P[Throwable, AnyRef] .If the members of P are mutable variables, the same variance annotation becomesillegal. abstract class Q[+A, +B](x: A, y: B) { var fst: A = x// **** error: illegal variance:var snd: B = y// `A', `B' occur in invariant position.}If the mutable variables are object-private, the class definition becomes legal again: abstract class R[+A, +B](x: A, y: B) {private[this] var fst: A = x// OKprivate[this] var snd: B = y// OK}Example 4.5.2 The following variance annotation is illegal, since a appears in con- travariant position in the parameter of append:abstract class Sequence[+A] {def append(x: Sequence[A]) : Sequence[A]// **** error: illegal variance:// `A' occurs in contravariant position. }-------------------------------------------------------------------------------46Basic Declarations and DefinitionsThe problem can be avoided by generalizing the type of append by means of a lower bound:abstract class Sequence[+A] {def append[B >: A](x: Sequence[B]) : Sequence[B]}Example 4.5.3 Here is a case where a contravariant type parameter is useful. abstract class OutputChannel[-A] {def write(x: A) : Unit}With that annotation, we have that OutputChannel[AnyRef] conforms toOutputChannel[String]. That is, a channel on which one can write any object can substitute for a channel on which one can write only strings.4.6Function Declarations and DefinitionsSyntax:Dcl::=`def' FunDclFunDcl ::=FunSig `:' TypeDef::=`def' FunDefFunDef::=FunSig [`:' Type] `=' ExprFunSig::=id [FunTypeParamClause] ParamClauses FunTypeParamClause ::=`[' TypeParam {`,' TypeParam} `]'ParamClauses::={ParamClause} [[nl] `(' `implicit' Params `) ']ParamClause ::=[nl] `(' [Params] `) '}Params::=Param {`,' Param}Param::={Annotation} id [`:' ParamType] [`=' Expr]ParamType ::=Type|`=>' Type|Type `*'A function declaration has the form def f psig: T , where f is the function'sname, psig is its parameter signature and T is its result type. A function definition def f psig: T = e also includes a function body e, i.e. an expression which definesthe function's result. A parameter signature consists of an optional type parameterclause [tps ], followed by zero or more value parameter clauses (ps1) ...(psn) . Such a declaration or definition introduces a value with a (possibly polymorphic) methodtype whose parameter types and result type are as given.The type of the function body is expected to conform (§6.1) to the function's de- clared result type, if one is given. If the function definition is not recursive, the re--------------------------------------------------------------------------------4.6 Function Declarations and Definitions 47sult type may be omitted, in which case it is determined from the packed type of thefunction body.A type parameter clause tps consists of one or more type declarations (§4.3) ,which introduce type parameters, possibly with bounds. The scope of a type parameterincludes the whole signature, including any of the type parameter bounds as well asthe function body, if it is present. A value parameter clause ps consists of zero or more formal parameter bindingssuch as x: T or x : T = e, which bind value parameters and associate them withtheir types. Each value parameter declaration may optionally define a default argu- ment. The default argument expression e is type-checked with an expected type Tobtained by replacing all occurences of the function's type parameters in T by theundefined type.For every parameter pi,j with a default argument a method named f $default$n is generated which computes the default argument expression. Here, n denotes theparameter's position in the method declaration. These methods are parametrizedby the type parameter clause [tps ] and all value parameter clauses (ps1) ...(psi-1) preceeding pi,j . The f $default$n methods are inaccessible for user programs.The scope of a formal value parameter name x comprises all subsequent parameterclauses, as well as the method return type and the function body, if they are given.1 Both type parameter names and value parameter names must be pairwise distinct.Example 4.6.1 In the methoddef compare[T](a: T = 0) (b: T = a) = (a == b)the default expression 0 is type-checked with an undefined expected type. When applying compare() , the default value 0 is inserted and T is instantiated to Int. Themethods computing the default arguments have the form:def compare$default$1[T]: Int = 0def compare$default$2[T](a: T) : T = a 4.6.1 By-Name ParametersSyntax:ParamType::=`=>' TypeThe type of a value parameter may be prefixed by =>, e.g. x: => T . The type ofsuch a parameter is then the parameterless method type => T . This indicates that the corresponding argument is not evaluated at the point of function application,1However, at present singleton types of method parameters may only appear in the methodbody; so dependent method types are not supported. -------------------------------------------------------------------------------48Basic Declarations and Definitionsbut instead is evaluated at each use within the function. That is, the argument is evaluated using call-by-name.The by-name modifier is disallowed for parameters of classes that carry a val orvar prefix, including parameters of case classes for which a val prefix is implicitly generated. The by-name modifier is also disallowed for implicit parameters (§7.2) .Example 4.6.2 The declarationdef whileLoop (cond: => Boolean) (stat: => Unit) : Unitindicates that both parameters of whileLoop are evaluated using call-by-name. 4.6.2 Repeated ParametersSyntax:ParamType::=Type `*'The last value parameter of a parameter section may be suffixed by "*", e.g.(..., x:T *) . The type of such a repeated parameter inside the method is then the sequence type scala.Seq[T ]. Methods with repeated parameters T * takea variable number of arguments of type T . That is, if a method m with type(p1 : T1, . . . , pn : Tn, ps : S*) U is applied to arguments (e1, . . . , ek) where k n, then m is taken in that application to have type (p1 : T1, ..., pn : Tn, ps : S, ..., ps S) U ,with k - n occurrences of type S where any parameter names beyond ps arefresh. The only exception to this rule is if the last argument is marked to be a sequence argument via a * type annotation. If m above is applied to argu-ments (e1, ..., en,e : *) , then the type of m in that application is taken to be(p1 : T1, . . . , pn : Tn, ps :scala.Seq[S]) . It is not allowed to define any default arguments in a parameter section with a re-peated parameter.Example 4.6.3 The following method definition computes the sum of the squaresof a variable number of integer arguments. def sum(args: Int*) = {var result = 0for (arg <- args) result += arg * argresult}The following applications of this method yield 0, 1, 6, in that order. sum()sum(1)sum(1, 2, 3)-------------------------------------------------------------------------------4.6 Function Declarations and Definitions49Furthermore, assume the definition: val xs = List(1, 2, 3)The following application of method sum is ill-formed:sum(xs)// ***** error: expected: Int, found: List[Int]By contrast, the following application is well formed and yields again the result 6: sum(xs: *)4.6.3 ProceduresSyntax:FunDcl::=FunSigFunDef::=FunSig [nl] `{' Block `}'Special syntax exists for procedures, i.e. functions that return the Unit value () . A procedure declaration is a function declaration where the result type is omitted.The result type is then implicitly completed to the Unit type. E.g., def f (ps) isequivalent to def f (ps) : Unit. A procedure definition is a function definition where the result type and the equalssign are omitted; its defining expression must be a block. E.g., def f (ps) {stats} isequivalent to def f (ps) : Unit = {stats}. Example 4.6.4 Here is a declaration and a definition of a procedure named write:trait Writer {def write(str: String)}object Terminal extends Writer {def write(str: String) { System.out.println(str) } }The code above is implicitly completed to the following code:trait Writer {def write(str: String) : Unit}object Terminal extends Writer {def write(str: String) : Unit = { System.out.println(str) } }-------------------------------------------------------------------------------50Basic Declarations and Definitions4.6.4 Method Return Type InferenceA class member definition m that overrides some other function m in a base class of C may leave out the return type, even if it is recursive. In this case, the return typeR of the overridden function m , seen as a member of C , is taken as the return typeof m for each recursive invocation of m. That way, a type R for the right-hand side of m can be determined, which is then taken as the return type of m. Note that Rmay be different from R , as long as R conforms to R .Example 4.6.5 Assume the following definitions:trait I { def factorial(x: Int) : Int}class C extends I {def factorial(x: Int) = if (x == 0) 1 else x * factorial(x - 1)}Here, it is OK to leave out the result type of factorial in C, even though the method is recursive.4.7Import ClausesSyntax:Import::= `import' ImportExpr {`,' ImportExpr}ImportExpr::= StableId `.' (id | `' | ImportSelectors) ImportSelectors ::= `{' {ImportSelector `,'}(ImportSelector | `') `}'ImportSelector::= id [`=>' id | `=>' `']An import clause has the form import p.I where p is a stable identifier (§3.1) and I is an import expression. The import expression determines a set of names of im-portable members of p which are made available without qualification. A memberm of p is importable if it is not object-private (§5.2) .The most general form of an import expression is a list of import selectors{ x1 => y1, . . . , xn => yn, _ } .for n 0, where the final wildcard `' may be absent. It makes available each im-portable member p.xi under the unqualified name yi . I.e. every import selector xi => yi renames p.xi to yi . If a final wildcard is present, all importable mem-bers z of p other than x1, ..., xn, y1, ..., yn are also made available under their ownunqualified names. Import selectors work in the same way for type and term members. For instance, an-------------------------------------------------------------------------------4.7 Import Clauses51 import clause import p.{x => y } renames the term name p.x to the term namey and the type name p.x to the type name y. At least one of these two names mustreference an importable member of p. If the target in an import selector is a wildcard, the import selector hides access tothe source member. For instance, the import selector x => _ "renames" x to thewildcard symbol (which is unaccessible as a name in user programs) , and thereby effectively prevents unqualified access to x. This is useful if there is a final wild-card in the same import selector list, which imports all members not mentioned inprevious import selectors. The scope of a binding introduced by an import-clause starts immediately after theimport clause and extends to the end of the enclosing block, template, packageclause, or compilation unit, whichever comes first. Several shorthands exist. An import selector may be just a simple name x. Inthis case, x is imported without renaming, so the import selector is equivalent tox => x. Furthermore, it is possible to replace the whole import selector list by a single identifier or wildcard. The import clause import p.x is equivalent toimport p.{x } , i.e. it makes available without qualification the member x of p. Theimport clause import p._ is equivalent to import p.{}, i.e. it makes available without qualification all members of p (this is analogous to import p.* in Java) .An import clause with multiple import expressions import p1.I1, ..., pn.In is in-terpreted as a sequence of import clauses import p1.I1; ...; import pn.In. Example 4.7.1 Consider the object definition:object M {def z = 0, one = 1def add(x: Int, y: Int) : Int = x + y}Then the block{ import M.{one, z => zero, }; add(zero, one) } is equivalent to the block{ M.add(M.z, M.one) } .-------------------------------------------------------------------------------------------------------------------------------------------------------------- Chapter 5Classes and ObjectsSyntax:TmplDef::= [`case'] `class' ClassDef|[`case'] `object' ObjectDef|`trait' TraitDef Classes (§5.3) and objects (§5.4) are both defined in terms of templates.5.1TemplatesSyntax:ClassTemplate::=[EarlyDefs] ClassParents [TemplateBody] TraitTemplate::=[EarlyDefs] TraitParents [TemplateBody]ClassParents::=Constr {`with' AnnotType}TraitParents::=AnnotType {`with' AnnotType} TemplateBody::=[nl] `{' [SelfType] TemplateStat {semi TemplateStat} `}'SelfType::=id [`:' Type] `=>'|this `:' Type `=>' A template defines the type signature, behavior and initial state of a traitor class of objects or of a single object.Templates form part of instancecreation expressions, class definitions, and object definitions. A templatesc with mt1 with ... with mtn {stats} consists of a constructor invocation scwhich defines the template's superclass, trait references mt1, ..., mtn (n 0) , whichdefine the template's traits, and a statement sequence stats which contains initial- ization code and additional member definitions for the template.Each trait reference mti must denote a trait (§5.3.3) .By contrast, the superclassconstructor sc normally refers to a class which is not a trait. It is possible to write -------------------------------------------------------------------------------54Classes and Objectsa list of parents that starts with a trait reference, e.g. mt1 with ... with mtn. In that case the list of parents is implicitly extended to include the supertype of mt1as first parent type. The new supertype must have at least one constructor thatdoes not take parameters. In the following, we will always assume that this implicit extension has been performed, so that the first parent class of a template is a regularsuperclass constructor, not a trait reference.The list of parents of every class is also always implicitly extended by a reference to the scala.ScalaObject trait as last mixin. E.g.sc with mt1 with ... with mtn {stats}becomesmt1 with ... with mtn with ScalaObject {stats}.The list of parents of a template must be well-formed. This means that the class denoted by the superclass constructor sc must be a subclass of the superclassesof all the traits mt1, ..., mtn. In other words, the non-trait classes inherited by atemplate form a chain in the inheritance hierarchy which starts with the template's superclass.The least proper supertype of a template is the class type or compound type (§3.2.7)consisting of all its parent class types.The statement sequence stats contains member definitions that define new mem- bers or overwrite members in the parent classes. If the template forms part of anabstract class or trait definition, the statement part stats may also contain declara-tions of abstract members. If the template forms part of a concrete class definition, stats may still contain declarations of abstract type members, but not of abstractterm members. Furthermore, stats may in any case also contain expressions; theseare executed in the order they are given as part of the initialization of a template. The sequence of template statements may be prefixed with a formal parameter def-inition and an arrow, e.g. x =>, or x:T =>. If a formal parameter is given, it canbe used as an alias for the reference this throughout the body of the template. If the formal parameter comes with a type T , this definition affects the self type S ofthe underlying class or object as follows: Let C be the type of the class or trait orobject defining the template. If a type T is given for the formal self parameter, S is the greatest lower bound of T and C . If no type T is given, S is just C . Inside thetemplate, the type of this is assumed to be S.The self type of a class or object must conform to the self types of all classes which are inherited by the template t .A second form of self type annotation reads just this: S =>. It prescribes the typeS for this without introducing an alias name for it.Example 5.1.1 Consider the following class definitions: -------------------------------------------------------------------------------5.1 Templates55class Base extends Object {}trait Mixin extends Base {}object O extends Mixin {} In this case, the definition of O is expanded to:object O extends Base with Mixin {}Inheriting from Java Types.A template may have a Java class as its superclass andJava interfaces as its mixins. Template Evaluation.Consider a template sc with mt1 with mtn {stats}.If this is the template of a trait (§5.3.3) then its mixin-evaluation consists of an eval-uation of the statement sequence stats. If this is not a template of a trait, then its evaluation consists of the following steps.· First, the superclass constructor sc is evaluated (§5.1.1) .· Then, all base classes in the template's linearization (§5.1.2) up to the tem- plate's superclass denoted by sc are mixin-evaluated. Mixin-evaluation hap-pens in reverse order of occurrence in the linearization.· Finally the statement sequence stats is evaluated. Delayed Initializaton.The initialization code of an object or class (but not atrait) that follows the superclass constructor invocation and the mixin-evaluationof the template's base classes is passed to a special hook, which is inaccessible from user code. Normally, that hook simply executes the code that is passed toit. But templates inheriting the scala.DelayedInit trait can override the hook byre-implementing the delayedInit method, which is defined as follows: def delayedInit(body: => Unit)5.1.1 Constructor InvocationsSyntax:Constr::=AnnotType {`(' [Exprs] `) '}Constructor invocations define the type, members, and initial state of objects cre- ated by an instance creation expression, or of parts of an object's definition whichare inherited by a class or object definition. A constructor invocation is a functionapplication x.c[targs](args1) ...(argsn) , where x is a stable identifier (§3.1) ,c is a type name which either designates a class or defines an alias type for one, targs is a-------------------------------------------------------------------------------56Classes and Objects type argument list, args1, ..., argsn are argument lists, and there is a constructor ofthat class which is applicable (§6.6) to the given arguments. If the constructor invo-cation uses named or default arguments, it is transformed into a block expression using the same transformation as described in (§6.6.1) .The prefix `x.' can be omitted. A type argument list can be given only if the class ctakes type parameters. Even then it can be omitted, in which case a type argument list is synthesized using local type inference (§6.26.4) .If no explicit arguments aregiven, an empty list () is implicitly supplied.An evaluation of a constructor invocation x.c[targs](args1) ...(argsn) consists of the following steps:· First, the prefix x is evaluated.· Then, the arguments args1, ..., argsn are evaluated from left to right.· Finally, the class being constructed is initialized by evaluating the template of the class referred to by c.5.1.2 Class LinearizationThe classes reachable through transitive closure of the direct inheritance relationfrom a class C are called the base classes of C . Because of mixins, the inheritance re- lationship on base classes forms in general a directed acyclic graph. A linearizationof this graph is defined as follows.Definition 5.1.2 Let C be a class with template C1 with ... with Cn { stats }. The linearization of C , L (C ) is defined as follows:L (C) = C , L (Cn) + ... + L (C1)Here + denotes concatenation where elements of the right operand replace identi-cal elements of the left operand: {a, A} + B = a,(A + B) ifa B= A + Bifa BExample 5.1.3 Consider the following class definitions.abstract class AbsIterator extends AnyRef { ... }trait RichIterator extends AbsIterator { ... } class StringIterator extends AbsIterator { ... }class Iter extends StringIterator with RichIterator { ... }Then the linearization of class Iter is{ Iter, RichIterator, StringIterator, AbsIterator, ScalaObject, AnyRef, Any } -------------------------------------------------------------------------------5.1 Templates57Trait ScalaObject appears in this list because it is added as last mixin to every Scala class (§5.1) .Note that the linearization of a class refines the inheritance relation: if C is a sub-class of D, then C precedes D in any linearization where both C and D occur. Defi- nition 5.1.2also satisfies the property that a linearization of a class always containsthe linearization of its direct superclass as a suffix. For instance, the linearization ofStringIterator is { StringIterator, AbsIterator, ScalaObject, AnyRef, Any }which is a suffix of the linearization of its subclass Iter. The same is not true for thelinearization of mixins. For instance, the linearization of RichIterator is { RichIterator, AbsIterator, ScalaObject, AnyRef, Any }which is not a suffix of the linearization of Iter.5.1.3 Class MembersA class C defined by a template C1 with ... with Cn { stats } can define mem- bers in its statement sequence stats and can inherit members from all parentclasses. Scala adopts Java and C#'s conventions for static overloading of methods. Itis thus possible that a class defines and/or inherits several methods with the same name. To decide whether a defined member of a class C overrides a member of aparent class, or whether the two co-exist as overloaded variants in C , Scala uses thefollowing definition of matching on members: Definition 5.1.4 A member definition M matches a member definition M , if M andM bind the same name, and one of following holds.1. Neither M nor M is a method definition.2. M and M define both monomorphic methods with equivalent argument types.3. M defines a parameterless method and M defines a method with an emptyparameter list () or vice versa.4. M and M define both polymorphic methods with equal number of argument types T , T and equal numbers of type parameters t , t , say, and T = [t /t]T .Member definitions fall into two categories: concrete and abstract. Members ofclass C are either directly defined (i.e. they appear in C 's statement sequence stats) or they are inherited. There are two rules that determine the set of members of aclass, one for each category:------------------------------------------------------------------------------- 58Classes and ObjectsDefinition 5.1.5 A concrete member of a class C is any concrete definition M insome class Ci  L (C ) , except if there is a preceding class C j  L (C ) where j < i which directly defines a concrete member M matching M .An abstract member of a class C is any abstract definition M in some class Ci  L (C ) ,except if C contains already a concrete member M matching M , or if there is a preceding class C j  L (C ) where j < i which directly defines an abstract memberM matching M .This definition also determines the overriding relationships between matchingmembers of a class C and its parents (§5.1.4) .First, a concrete definition always overrides an abstract definition. Second, for definitions M and M ' which are bothconcrete or both abstract, M overrides M if M appears in a class that precedes (inthe linearization of C ) the class in which M is defined. It is an error if a template directly defines two matching members. It is also an errorif a template contains two members (directly defined or inherited) with the samename and the same erased type (§3.7) .Finally, a template is not allowed to contain two methods (directly defined or inherited) with the same name which both definedefault arguments.Example 5.1.6 Consider the trait definitions:trait A { def f: Int }trait B extends A { def f: Int = 1 ; def g: Int = 2 ; def h: Int = 3 } trait C extends A { override def f: Int = 4 ; def g: Int }trait D extends B with C { def h: Int }Then trait D has a directly defined abstract member h. It inherits member f fromtrait C and member g from trait B. 5.1.4 OverridingA member M of class C that matches (§5.1.3) a non-private member M of a baseclass of C is said to override that member. In this case the binding of the overrid-ing member M must subsume (§3.5.2) the binding of the overridden member M . Furthermore, the following restrictions on modifiers apply to M and M :· M must not be labeled final.· M must not be private (§5.2) .· If M is labeled private[C ] for some enclosing class or package C , then M must be labeled private[C ] for some class or package C where C equals Cor C is contained in C .· If M is labeled protected, then M must also be labeled protected.------------------------------------------------------------------------------- 5.1 Templates59· If M is not an abstract member, then M must be labeled override. Further-more, one of two possibilities must hold:­ either M is defined in a subclass of the class where is M is defined, ­ or both M and M override a third member M which is defined in a baseclass of both the classes containing M and M· If M is incomplete (§5.2) in C then M must be labeled abstract override. · If M and M are both concrete value definitions, then either none of them ismarked lazy or both must be marked lazy.A special rule concerns parameterless methods. If a paramterless method defined as def f : T = ... or def f = ... overrides a method of type () T which has anempty parameter list, then f is also assumed to have an empty parameter list.Another restriction applies to abstract type members: An abstract type member with a volatile type (§3.6) as its upper bound may not override an abstract typemember which does not have a volatile upper bound.An overriding method inherits all default arguments from the definition in the su- perclass. By specifying default arguments in the overriding method it is possible toadd new defaults (if the corresponding parameter in the superclass does not have adefault) or to override the defaults of the superclass (otherwise) . Example 5.1.7 Consider the definitions:trait Root { type T <: Root }trait A extends Root { type T <: A }trait B extends Root { type T <: B }trait C extends A with B Then the class definition C is not well-formed because the binding of T in C istype T <: B, which fails to subsume the binding type T <: A of T in type A. Theproblem can be solved by adding an overriding definition of type T in class C: class C extends A with B { type T <: C }5.1.5 Inheritance ClosureLet C be a class type. The inheritance closure of C is the smallest set S of types suchthat· If T is in S , then every type T which forms syntactically a part of T is also in S .· If T is a class type in S , then all parents (§5.1) of T are also in S .It is a static error if the inheritance closure of a class type consists of an infinite num-ber of types. (This restriction is necessary to make subtyping decidable [KP07]) . -------------------------------------------------------------------------------60Classes and Objects5.1.6 Early DefinitionsSyntax:EarlyDefs::= `{' [EarlyDef {semi EarlyDef}] `}' `with' EarlyDef::={Annotation} {Modifier} PatVarDefA template may start with an early field definition clause, which serves to definecertain field values before the supertype constructor is called. In a template { val p1: T1 = e1...val pn: Tn = en} with sc with mt1 with mtn {stats}The initial pattern definitions of p1, ..., pn are called early definitions. They definefields which form part of the template. Every early definition must define at least one variable.An early definition is type-checked and evaluated in the scope which is in effectjust before the template being defined, augmented by any type parameters of theenclosing class and by any early definitions preceding the one being defined. In particular, any reference to this in the right-hand side of an early definition refersto the identity of this just outside the template. Consequently, it is impossible thatan early definition refers to the object being constructed by the template, or refers to one of its fields and methods, except for any other preceding early definition in thesame section. Furthermore, references to preceding early definitions always refer tothe value that's defined there, and do not take into account overriding definitions. In other words, a block of early definitions is evaluated exactly as if it was a localbock containing a number of value definitions.Early definitions are evaluated in the order they are being defined before the super- class constructor of the template is called.Example 5.1.8 Early definitions are particularly useful for traits, which do not havenormal constructor parameters. Example:trait Greeting { val name: Stringval msg = "How are you, "+name}class C extends {val name = "Bob"} with Greeting {println(msg)} In the code above, the field name is initialized before the constructor of Greeting-------------------------------------------------------------------------------5.2 Modifiers61 is called.Therefore, field msg in class Greeting is properly initialized to"How are you, Bob".If name had been initialized instead in C's normal class body, it would be initial- ized after the constructor of Greeting. In that case, msg would be initialized to"How are you, <null>".5.2ModifiersSyntax:Modifier::= LocalModifier|AccessModifier|`override'LocalModifier::=`abstract'|`final'|`sealed' |`implicit'|`lazy'AccessModifier::=(`private' | `protected') [AccessQualifier]AccessQualifier::=`[' (id | `this') `]' Member definitions may be preceded by modifiers which affect the accessibility andusage of the identifiers bound by them. If several modifiers are given, their orderdoes not matter, but the same modifier may not occur more than once. Modifiers preceding a repeated definition apply to all constituent definitions. The rules gov-erning the validity and meaning of a modifier are as follows.· The private modifier can be used with any definition or declaration in a tem- plate. Such members can be accessed only from within the directly enclos-ing template and its companion module or companion class (§5.4) .They arenot inherited by subclasses and they may not override definitions in parent classes.The modifier can be qualified with an identifier C (e.g. private[C ]) that mustdenote a class or package enclosing the definition. Members labeled withsuch a modifier are accessible respectively only from code inside the pack- age C or only from code inside the class C and its companion module (§5.4) .Such members are also inherited only from templates inside C .An different form of qualification is private[this]. A member M marked with this modifier can be accessed only from within the object in which it isdefined. That is, a selection p.M is only legal if the prefix is this or O.this,for some class O enclosing the reference. In addition, the restrictions for un- qualified private apply.-------------------------------------------------------------------------------62Classes and ObjectsMembers marked private without a qualifier are called class-private, whereas members labeled with private[this] are called object-private. A memberis private if it is either class-private or object-private, but not if it is markedprivate[C ] where C is an identifier; in the latter case the member is called qualified private.Class-private or object-private members may not be abstract, and may nothave protected or override modifiers.· The protected modifier applies to class member definitions. Protected mem- bers of a class can be accessed from within­ the template of the defining class,­ all templates that have the defining class as a base class,­ the companion module of any of those classes. A protected modifier can be qualified with an identifier C(e.g.protected[C ]) that must denote a class or package enclosing the defi-nition. Members labeled with such a modifier are also accessible respectively from all code inside the package C or from all code inside the class C and itscompanion module (§5.4) .A protected identifier x may be used as a member name in a selection r .xonly if one of the following applies: ­ The access is within the template defining the member, or, if a qualifi-cation C is given, inside the package C , or the class C , or its companionmodule, or­ r is one of the reserved words this and super, or ­ r 's type conforms to a type-instance of the class which contains the ac-cess.A different form of qualification is protected[this]. A member M markedwith this modifier is called object-protected; it can be accessed only from within the object in which it is defined. That is, a selection p.M is only le-gal if the prefix is this or O.this, for some class O enclosing the reference. Inaddition, the restrictions for unqualified protected apply. · The override modifier applies to class member definitions or declarations. Itis mandatory for member definitions or declarations that override some otherconcrete member definition in a parent class. If an override modifier is given, there must be at least one overridden member definition or declaration (ei-ther concrete or abstract) .· The override modifier has an additional significance when combined withthe abstract modifier. That modifier combination is only allowed for value members of traits.-------------------------------------------------------------------------------5.2 Modifiers63We call a member M of a template incomplete if it is either abstract (i.e. de- fined by a declaration) , or it is labeled abstract and override and every mem-ber overridden by M is again incomplete.Note that the abstract override modifier combination does not influence the concept whether a member is concrete or abstract. A member is abstractif only a declaration is given for it; it is concrete if a full definition is given.· The abstract modifier is used in class definitions. It is redundant for traits, and mandatory for all other classes which have incomplete members. Ab-stract classes cannot be instantiated (§6.10) with a constructor invocation un-less followed by mixins and/or a refinement which override all incomplete members of the class. Only abstract classes and traits can have abstract termmembers.The abstract modifier can also be used in conjunction with override forclass member definitions. In that case the previous discussion applies. · The final modifier applies to class member definitions and to class defini-tions. A final class member definition may not be overridden in subclasses.A final class may not be inherited by a template. final is redundant for ob- ject definitions. Members of final classes or objects are implicitly also final, sothe final modifier is generally redundant for them, too. Note, however, thatconstant value definitions (§4.1) do require an explicit final modifier, even if they are defined in a final class or object. final may not be applied to incom-plete members, and it may not be combined in one modifier list with sealed.· The sealed modifier applies to class definitions. A sealed class may not be di- rectly inherited, except if the inheriting template is defined in the same sourcefile as the inherited class. However, subclasses of a sealed class can be inher-ited anywhere.· The lazy modifier applies to value definitions. A lazy value is initialized the first time it is accessed (which might never happen at all) . Attempting to ac-cess a lazy value during its initialization might lead to looping behavior. Ifan exception is thrown during initialization, the value is considered uninitial- ized, and a later access will retry to evaluate its right hand side.Example 5.2.1 The following code illustrates the use of qualified private:package outerpkg.innerpkgclass Outer { class Inner {private[Outer] def f()private[innerpkg] def g()private[outerpkg] def h()}}------------------------------------------------------------------------------- 64Classes and ObjectsHere, accesses to the method f can appear anywhere within OuterClass, butnot outside it. Accesses to method g can appear anywhere within the packageouterpkg.innerpkg, as would be the case for package-private methods in Java. Fi- nally, accesses to method h can appear anywhere within package outerpkg, includ-ing packages contained in it.Example 5.2.2 A useful idiom to prevent clients of a class from constructing new instances of that class is to declare the class abstract and sealed:object m {abstract sealed class C (x: Int) {def nextC = new C(x + 1) {}}val empty = new C(0) {} }For instance, in the code above clients can create instances of class m.C only by call-ing the nextC method of an existing m.C object; it is not possible for clients to createobjects of class m.C directly. Indeed the following two lines are both in error: new m.C(0)// **** error: C is abstract, so it cannot be instantiated.new m.C(0) {} // **** error: illegal inheritance from sealed class.A similar access restriction can be achieved by marking the primary constructor private (see Example 5.3.2) .5.3Class DefinitionsSyntax:TmplDef::=`class' ClassDefClassDef::=id [TypeParamClause] {Annotation} [AccessModifier] ClassParamClauses ClassTemplateOptClassParamClauses ::={ClassParamClause}[[nl] `(' implicit ClassParams `) ']ClassParamClause::= [nl] `(' [ClassParams] ') 'ClassParams::=ClassParam {`,' ClassParam}ClassParam::={Annotation} [{Modifier} (`val' | `var') ] id [`:' ParamType] [`=' Expr]ClassTemplateOpt::=`extends' ClassTemplate | [[`extends'] TemplateBody]The most general form of class definition isclass c[tps ] as m(ps1) ...(psn) extends t (n 0) .Here,-------------------------------------------------------------------------------5.3 Class Definitions65c is the name of the class to be defined. tps is a non-empty list of type parameters of the class being defined. Thescope of a type parameter is the whole class definition including the type pa-rameter section itself. It is illegal to define two type parameters with the same name. The type parameter section [tps ] may be omitted. A class with a typeparameter section is called polymorphic, otherwise it is called monomorphic.as is a possibly empty sequence of annotations (§11) .If any annotations are given, they apply to the primary constructor of the class.m is an access modifier (§5.2) such as private or protected, possibly witha qualification. If such an access modifier is given it applies to the primary constructor to the class.(ps1) ...(psn) are formal value parameter clauses for the primary constructorof the class. The scope of a formal value parameter includes all subsequentparameter sections and the template t . However, a formal value parameter may not form part of the types of any of the parent classes or members of theclass template t . It is illegal to define two formal value parameters with thesame name. If no formal parameter sections are given, an empty parameter section () is assumed.If a formal parameter declaration x : T is preceded by a val or var keyword, anaccessor (getter) definition (§4.2) for this parameter is implicitly added to the class. The getter introduces a value member x of class c that is defined as an alias of the parameter. If the introducing keyword is var, a setter accessor x=(§4.2) is also implicitly added to the class. In invocation of that setter x=(e)changes the value of the parameter to the result of evaluating e. The formal parameter declaration may contain modifiers, which then carry over to theaccessor definition(s) . A formal parameter prefixed by val or var may not atthe same time be a call-by-name parameter (§4.6.1) . t is a template (§5.1) of the formsc with mt1 with ... with mtm { stats }(m 0)which defines the base classes, behavior and initial state of objects of theclass. The extends clause extends sc with mt1 with ... with mtm can be omitted, in which case extends scala.AnyRef is assumed. The class body{stats } may also be omitted, in which case the empty body {} is assumed.This class definition defines a type c[tps ] and a constructor which when applied to parameters conforming to types ps initializes instances of type c[tps ] by evaluatingthe template t .Example 5.3.1 The following example illustrates val and var parameters of a class C: -------------------------------------------------------------------------------66Classes and Objectsclass C(x: Int, val y: String, var z: List[String])val c = new C(1, "abc", List() ) c.z = c.y :: c.zExample 5.3.2 The following class can be created only from its companion module.object Sensitive {def makeSensitive(credentials: Certificate) : Sensitive = if (credentials == Admin) new Sensitive() else throw new SecurityViolationException}class Sensitive private () {...}5.3.1 Constructor DefinitionsSyntax:FunDef::= `this' ParamClause ParamClauses (`=' ConstrExpr | [nl] ConstrBlock)ConstrExpr::= SelfInvocation|ConstrBlockConstrBlock::= `{' SelfInvocation {semi BlockStat} `}' SelfInvocation ::= `this' ArgumentExprs {ArgumentExprs}A class may have additional constructors besides the primary constructor. Theseare defined by constructor definitions of the form def this(ps1) ...(psn) = e. Such a definition introduces an additional constructor for the enclosing class, withparameters as given in the formal parameter lists ps1, ..., psn, and whose evaluationis defined by the constructor expression e. The scope of each formal parameter is the subsequent parameter sections and the constructor expression e. A constructorexpression is either a self constructor invocation this(args1) ...(argsn) or a blockwhich begins with a self constructor invocation. The self constructor invocation must construct a generic instance of the class. I.e. if the class in question has nameC and type parameters [tps ], then a self constructor invocation must generate aninstance of C [tps ]; it is not permitted to instantiate formal type parameters. The signature and the self constructor invocation of a constructor definition aretype-checked and evaluated in the scope which is in effect at the point of the en-closing class definition, augmented by any type parameters of the enclosing class and by any early definitions (§5.1.6) of the enclosing template. The rest of the con-structor expression is type-checked and evaluated as a function body in the currentclass.If there are auxiliary constructors of a class C , they form together with C 's primary -------------------------------------------------------------------------------5.3 Class Definitions67constructor (§5.3) an overloaded constructor definition. The usual rules for over- loading resolution (§6.26.3) apply for constructor invocations of C , including forthe self constructor invocations in the constructor expressions themselves. How-ever, unlike other methods, constructors are never inherited. To prevent infinite cycles of constructor invocations, there is the restriction that every self constructorinvocation must refer to a constructor definition which precedes it (i.e. it must referto either a preceding auxiliary constructor or the primary constructor of the class) . Example 5.3.3 Consider the class definitionclass LinkedList[A]() {var head = _var tail = nulldef isEmpty = tail != nulldef this(head: A) = { this() ; this.head = head } def this(head: A, tail: List[A]) = { this(head) ; this.tail = tail }}This defines a class LinkedList with three constructors. The second constructorconstructs an singleton list, while the third one constructs a list with a given head and tail.5.3.2 Case ClassesSyntax:TmplDef::=`case' `class' ClassDefIf a class definition is prefixed with case, the class is said to be a case class. The formal parameters in the first parameter section of a case class are called el-ements; they are treated specially. First, the value of such a parameter can be ex-tracted as a field of a constructor pattern. Second, a val prefix is implicitly added to such a parameter, unless the parameter carries already a val or var modifier. Hence,an accessor definition for the parameter is generated (§5.3) .A case class definition of c[tps ](ps1 ) ...(psn) with type parameters tps and value parameters ps implicitly generates an extractor object (§8.1.8) which is defined asfollows:object c {def apply[tps ](ps1 ) ...(psn) : c[tps] = new c[Ts](xs1 ) ...(xsn)def unapply[tps ](x: c[tps ]) = if (x eq null) scala.Noneelse scala.Some(x.xs11, . . . , x.xs1k)}Here, Ts stands for the vector of types defined in the type parameter section------------------------------------------------------------------------------- 68Classes and Objectstps, each xsi denotes the parameter names of the parameter section psi , andxs11, ..., xs1k denote the names of all parameters in the first parameter section xs1. If a type parameter section is missing in the class, it is also missing in the apply andunapply methods. The definition of apply is omitted if class c is abstract.If the case class definition contains an empty value parameter list, the unapply method returns a Boolean instead of an Option type and is defined as follows:def unapply[tps ](x: c[tps ]) = x ne nullThe name of the unapply method is changed to unapplySeq if the first parameter section ps1 of c ends in a repeated parameter of (§4.6.2) .If a companion objectc exists already, no new object is created, but the apply and unapply methods areadded to the existing object instead. A method named copy is implicitly added to every case class unless the class alreadyhas a member (directly defined or inherited) with that name. The method is definedas follows:def copy[tps ](ps ) . . .(ps 1n ) : c[tps ] = new c[Ts ](xs1 ) . . .(xsn )Again, Ts stands for the vector of types defined in the type parameter section tps andeach xsi denotes the parameter names of the parameter section ps . Every value iparameter psof the copy method has the form xi , ji , j :Ti , j =this.xi , j , where xi , j andTi,j refer to the name and type of the corresponding class parameter psi,j . Every case class implicitly overrides some method definitions of class scala.AnyRef(§12.1) unless a definition of the same method is already given in the case class itselfor a concrete definition of the same method is given in some base class of the case class different from AnyRef. In particular:Method equals: (Any) Boolean is structural equality, where two instancesare equal if they both belong to the case class in question and they have equal (with respect to equals) constructor arguments.Method hashCode: Int computes a hash-code. If the hashCode methods ofthe data structure members map equal (with respect to equals) values to equal hash-codes, then the case class hashCode method does too.Method toString: String returns a string representation which containsthe name of the class and its elements.Example 5.3.4 Here is the definition of abstract syntax for lambda calculus: class Exprcase class Var(x: String)extends Exprcase class Apply (f: Expr, e: Expr)extends Exprcase class Lambda(x: String, e: Expr) extends Expr -------------------------------------------------------------------------------5.3 Class Definitions69This defines a class Expr with case classes Var, Apply and Lambda. A call-by-value evaluator for lambda expressions could then be written as follows.type Env = String => Valuecase class Value(e: Expr, env: Env)def eval(e: Expr, env: Env) : Value = e match { case Var (x) =>env(x)case Apply(f, g) =>val Value(Lambda (x, e1) , env1) = eval(f, env)val v = eval(g, env)eval (e1, (y => if (y == x) v else env1(y) )) case Lambda(, ) =>Value(e, env)}It is possible to define further case classes that extend type Expr in other parts of theprogram, for instancecase class Number(x: Int) extends Expr This form of extensibility can be excluded by declaring the base class Expr sealed;in this case, all classes that directly extend Expr must be in the same source file asExpr.5.3.3 Traits Syntax:TmplDef::=`trait' TraitDefTraitDef::=id [TypeParamClause] TraitTemplateOptTraitTemplateOpt ::=`extends' TraitTemplate | [[`extends'] TemplateBody] A trait is a class that is meant to be added to some other class as a mixin. Unlikenormal classes, traits cannot have constructor parameters. Furthermore, no con-structor arguments are passed to the superclass of the trait. This is not necessary as traits are initialized after the superclass is initialized.Assume a trait D defines some aspect of an instance x of type C (i.e. D is a base classof C ) . Then the actual supertype of D in x is the compound type consisting of all the base classes in L (C ) that succeed D. The actual supertype gives the context forresolving a super reference in a trait (§6.5) .Note that the actual supertype dependson the type to which the trait is added in a mixin composition; it is not statically known at the time the trait is defined.If D is not a trait, then its actual supertype is simply its least proper supertype (whichis statically known) .------------------------------------------------------------------------------- 70Classes and ObjectsExample 5.3.5 The following trait defines the property of being comparable to ob-jects of some type. It contains an abstract method < and default implementations of the other comparison operators <=, >, and >=.trait Comparable[T <: Comparable[T]] { self: T =>def < (that: T) : Booleandef <=(that: T) : Boolean = this < that || this == that def > (that: T) : Boolean = that < thisdef >=(that: T) : Boolean = that <= this}Example 5.3.6 Consider an abstract class Table that implements maps from a type of keys A to a type of values B. The class has a method set to enter a new key / value pair into the table, and a method get that returns an optional value matchinga given key. Finally, there is a method apply which is like get, except that it returnsa given default value if the table is undefined for the given key. This class is imple- mented as follows.abstract class Table[A, B](defaultValue: B) {def get(key: A) : Option[B]def set(key: A, value: B)def apply(key: A) = get(key) match {case Some(value) => value case None => defaultValue}}Here is a concrete implementation of the Table class.class ListTable[A, B](defaultValue: B) extends Table[A, B](defaultValue) {private var elems: List[(A, B) ] = Nil def get(key: A) = elems.find(.1.==(key) ).map(.2)def set(key: A, value: B) { elems = (key, value) :: elems }}Here is a trait that prevents concurrent access to the get and set operations of its parent class:trait SynchronizedTable[A, B] extends Table[A, B] {abstract override def get(key: A) : Option[B] =synchronized { super.get(key) }abstract override def set(key: A, value: B) = synchronized { super.set(key, value) }}Note that SynchronizedTable does not pass an argument to its superclass, Table,even though Table is defined with a formal parameter. Note also that the super calls -------------------------------------------------------------------------------5.4 Object Definitions71in SynchronizedTable's get and set methods statically refer to abstract methods in class Table. This is legal, as long as the calling method is labeled abstract override(§5.2) .Finally, the following mixin composition creates a synchronized list table withstrings as keys and integers as values and with a default value 0: object MyTable extends ListTable[String, Int](0) with SynchronizedTable[String, Int]The object MyTable inherits its get and set method from SynchronizedTable. Thesuper calls in these methods are re-bound to refer to the corresponding imple- mentations in ListTable, which is the actual supertype of SynchronizedTable inMyTable.5.4Object DefinitionsSyntax:ObjectDef::=id ClassTemplate An object definition defines a single object of a new class. Its most general form isobject m extends t . Here, m is the name of the object to be defined, and t is atemplate (§5.1) of the form sc with mt1 with ... with mtn { stats }which defines the base classes, behavior and initial state of m.The extendsclause extends sc with mt1 with ... with mtn can be omitted, in which case extends scala.AnyRef is assumed. The class body {stats } may also be omitted,in which case the empty body {} is assumed.The object definition defines a single object (or: module) conforming to the tem- plate t . It is roughly equivalent to the following definition of a lazy value:lazy val m = new sc with mt1 with . . . with mtn { this: m.t y pe => stats }Note that the value defined by an object definition is instantiated lazily. Thenew m$cls constructor is evaluated not at the point of the object definition, but isinstead evaluated the first time m is dereferenced during execution of the program(which might be never at all) . An attempt to dereference m again in the course of evaluation of the constructor leads to a infinite loop or run-time error. Otherthreads trying to dereference m while the constructor is being evaluated block untilevaluation is complete. The expansion given above is not accurate for top-level objects. It cannot be be-cause variable and method definition cannot appear on the top-level outside of apackage object (§9.3) .Instead, top-level objects are translated to static fields. -------------------------------------------------------------------------------72Classes and ObjectsExample 5.4.1 Classes in Scala do not have static members; however, an equivalent effect can be achieved by an accompanying object definition E.g.abstract class Point {val x: Doubleval y: Doubledef isOrigin = (x == 0.0 && y == 0.0)} object Point {val origin = new Point() { val x = 0.0; val y = 0.0 }}This defines a class Point and an object Point which contains origin as a member.Note that the double use of the name Point is legal, since the class definition defines the name Point in the type name space, whereas the object definition defines aname in the term namespace.This technique is applied by the Scala compiler when interpreting a Java class with static members. Such a class C is conceptually seen as a pair of a Scala class thatcontains all instance members of C and a Scala object that contains all static mem-bers of C .Generally, a companion module of a class is an object which has the same name as the class and is defined in the same scope and compilation unit. Conversely, theclass is called the companion class of the module.------------------------------------------------------------------------------- Chapter 6ExpressionsSyntax:Expr::=(Bindings | id | `') `=>' Expr|Expr1Expr1::=`if' `(' Expr `) ' {nl} Expr [[semi] else Expr] |`while' `(' Expr `) ' {nl} Expr|`try' `{' Block `}' [`catch'`{' CaseClauses `}'][`finally' Expr]| `do' Expr [semi] `while' `(' Expr ') ' |`for' (`(' Enumerators `) ' | `{' Enumerators `}'){nl} [`yield'] Expr|`throw' Expr|`return' [Expr]| [SimpleExpr `.'] id `=' Expr|SimpleExpr1 ArgumentExprs `=' Expr|PostfixExpr|PostfixExpr Ascription|PostfixExpr `match' `{' CaseClauses `}' PostfixExpr::=InfixExpr [id [nl]]InfixExpr::=PrefixExpr|InfixExpr id [nl] InfixExprPrefixExpr::=[`-' | `+' | `~' | `!'] SimpleExpr SimpleExpr::=`new' (ClassTemplate | TemplateBody)|BlockExpr|SimpleExpr1 [`']SimpleExpr1::=Literal | Path|`'|`(' [Exprs] `) '|SimpleExpr `.' id s|SimpleExpr TypeArgs------------------------------------------------------------------------------- 74Expressions|SimpleExpr1 ArgumentExprs|XmlExprExprs::=Expr {`,' Expr}BlockExpr::=`{' CaseClauses `}' |`{' Block `}'Block::={BlockStat semi} [ResultExpr]ResultExpr::=Expr1|(Bindings | ([`implicit'] id | `') `:' CompoundType) `=>' Block Ascription::=`:' InfixType|`:' Annotation {Annotation}|`:' `' `*'Expressions are composed of operators and operands. Expression forms are dis- cussed subsequently in decreasing order of precedence.6.1Expression TypingThe typing of expressions is often relative to some expected type (which might beundefined) . When we write "expression e is expected to conform to type T ", we mean: (1) the expected type of e is T , and (2) the type of expression e must conformto T .The following skolemization rule is applied universally for every expression: If thetype of an expression would be an existential type T , then the type of the expression is assumed instead to be a skolemization (§3.2.10) of T .Skolemization is reversed by type packing. Assume an expression e of type T andlet t1[tps1] >: L1 <: U1, ..., tn[tpsn] >: Ln <: Un be all the type variables created by skolemization of some part of e which are free in T . Then the packed type of e isT forSome { type t1[tps1] >: L1 <: U1; ...; type tn[tpsn] >: Ln <: Un }.6.2Literals Syntax:SimpleExpr::=LiteralTyping of literals is as described in (§1.3) ;their evaluation is immediate.------------------------------------------------------------------------------- 6.3 The Null Value756.3The Null ValueThe null value is of type scala.Null, and is thus compatible with every referencetype. It denotes a reference value which refers to a special "null" object. This object implements methods in class scala.AnyRef as follows:· eq(x ) and ==(x ) return true iff the argument x is also the "null" object.· ne(x ) and !=(x ) return true iff the argument x is not also the "null" object. · isInstanceOf[T ] always returns false.· asInstanceOf[T ] returns the "null" object itself if Tconforms toscala.AnyRef, and throws a NullPointerException otherwise. Areferencetoanyothermemberofthe"null"objectcausesaNullPointerException to be thrown. 6.4DesignatorsSyntax:SimpleExpr::=Path|SimpleExpr `.' idA designator refers to a named term. It can be a simple name or a selection. A simple name x refers to a value as specified in §2.If x is bound by a definitionor declaration in an enclosing class or object C , it is taken to be equivalent to theselection C .this.x where C is taken to refer to the class containing x even if the type name C is shadowed (§2) at the occurrence of x.If r is a stable identifier (§3.1) of type T , the selection r.x refers statically to a termmember m of r that is identified in T by the name x. For other expressions e, e.x is typed as if it was { val y = e; y.x }, for some freshname y.The expected type of a designator's prefix is always undefined. The type of a desig-nator is the type T of the entity it refers to, with the following exception: The type of a path (§3.1) p which occurs in a context where a stable type (§3.2.1) is required isthe singleton type p.type.The contexts where a stable type is required are those that satisfy one of the follow- ing conditions:1. The path p occurs as the prefix of a selection and it does not designate a con-stant, or2. The expected type pt is a stable type, or------------------------------------------------------------------------------- 76Expressions3. The expected type pt is an abstract type with a stable type as lower bound,and the type T of the entity referred to by p does not conform to pt, or4. The path p designates a module. The selection e.x is evaluated by first evaluating the qualifier expression e, whichyields an object r , say. The selection's result is then the member of r that is eitherdefined by m or defined by a definition overriding m. If that member has a type which conforms to scala.NotNull, the member's value must be initialized to a valuedifferent from null, otherwise a scala.UnitializedError is thrown.6.5This and SuperSyntax: SimpleExpr::=[id `.'] `this'|[id '.'] `super' [ClassQualifier] `.' idThe expression this can appear in the statement part of a template or compound type. It stands for the object being defined by the innermost template or compoundtype enclosing the reference. If this is a compound type, the type of this is thatcompound type. If it is a template of a class or object definition with simple name C , the type of this is the same as the type of C .this.The expression C .this is legal in the statement part of an enclosing class or objectdefinition with simple name C . It stands for the object being defined by the inner- most such definition. If the expression's expected type is a stable type, or C .thisoccurs as the prefix of a selection, its type is C .this.type, otherwise it is the selftype of class C . A reference super.m refers statically to a method or type m in the least propersupertype of the innermost template containing the reference. It evaluates to themember m in the actual supertype of that template which is equal to m or which overrides m. The statically referenced member m must be a type or a method. Ifit is a method, it must be concrete, or the template containing the reference musthave a member m which overrides m and which is labeled abstract override. A reference C .super.m refers statically to a method or type m in the least propersupertype of the innermost enclosing class or object definition named C which en-closes the reference. It evaluates to the member m in the actual supertype of that class or object which is equal to m or which overrides m. The statically referencedmember m must be a type or a method. If the statically referenced member m isa method, it must be concrete, or the innermost enclosing class or object defini- tion named C must have a member m which overrides m and which is labeledabstract override.-------------------------------------------------------------------------------6.6 Function Applications 77The super prefix may be followed by a trait qualifier [T ], as in C .super[T ].x. Thisis called a static super reference. In this case, the reference is to the type or method ofx in the parent trait of C whose simple name is T . That member must be uniquely defined. If it is a method, it must be concrete.Example 6.5.1 Consider the following class definitionsclass Root { def x = "Root" }class A extends Root { override def x = "A" ; def superA = super.x } trait B extends Root { override def x = "B" ; def superB = super.x }class C extends Root with B {override def x = "C" ; def superC = super.x}class D extends A with B { override def x = "D" ; def superD = super.x}The linearization of class C is {C, B, Root} and the linearization of class D is{D, B, A, Root}. Then we have:(new A) .superA == "Root", (new C) .superB = "Root", (new C) .superC = "B",(new D) .superA == "Root", (new D) .superB = "A",(new D) .superD = "B",Note that the superB function returns different results depending on whether B is mixed in with class Root or A.6.6Function ApplicationsSyntax:SimpleExpr::=SimpleExpr1 ArgumentExprsArgumentExprs ::=`(' [Exprs] `) ' |`(' [Exprs `,'] PostfixExpr `:' `' `*' ') '|[nl] BlockExprExprs::=Expr {`,' Expr}An application f (e1, ..., em) applies the function f to the argument expressions e1, ..., em. If f has a method type (p1:T1, ..., pn:Tn) U , the type of each argumentexpression ei is typed with the corresponding parameter type Ti as expected type.Let Si be type type of argument ei (i = 1, ..., m) . If f is a polymorphic method, local type inference (§6.26.4) is used to determine type arguments for f . If f has somevalue type, the application is taken to be equivalent to f .apply(e1, ..., em) , i.e. theapplication of an apply method defined by f . The function f must be applicable to its arguments e1, ..., en of types S1, ..., Sn.-------------------------------------------------------------------------------78Expressions If f has a method type (p1 : T1, ..., pn : Tn) U we say that an argument expression eiis a named argument if it has the form xi = e and xii is one of the parameter namesp1, ..., pn. The function f is applicable if all of the follwing conditions hold: · For every named argument xi = e the type Sii is compatible with the parame-ter type T j whose name p j matches xi .· For every positional argument ei the type Si is compatible with Ti . · If the expected type is defined, the result type U is compatible to it.If f is a polymorphic method it is applicable if local type inference (§6.26.4) candetermine type arguments so that the instantiated method is applicable. If f has some value type it is applicable if it has a method member named apply which isapplicable.Evaluation of f (e1, ..., en) usually entails evaluation of f and e1, ..., en in that or-der. Each argument expression is converted to the type of its corresponding formal parameter. After that, the application is rewritten to the function's right hand side,with actual arguments substituted for formal parameters. The result of evaluatingthe rewritten right-hand side is finally converted to the function's declared result type, if one is given.The case of a formal parameter with a parameterless method type =>T is treatedspecially. In this case, the corresponding actual argument expression e is not eval- uated before the application. Instead, every use of the formal parameter on theright-hand side of the rewrite rule entails a re-evaluation of e. In other words, theevaluation order for =>-parameters is call-by-name whereas the evaluation order for normal parameters is call-by-value. Furthermore, it is required that e's packedtype (§6.1) conforms to the parameter type T . The behavior of by-name param-eters is preserved if the application is transformed into a block due to named or default arguments. In this case, the local value for that parameter has the formval yi = () => e and the argument passed to the function is yi () .The last argument in an application may be marked as a sequence argument, e.g. e: *. Such an argument must correspond to a repeated parameter (§4.6.2) of typeS* and it must be the only argument matching this parameter (i.e. the number offormal parameters and actual arguments must be the same) . Furthermore, the type of e must conform to scala.Seq[T ], for some type T which conforms to S. In thiscase, the argument list is transformed by replacing the sequence e with its elements.When the application uses named arguments, the vararg parameter has to be spec- ified exactly once.A function application usually allocates a new frame on the program's run-timestack. However, if a local function or a final method calls itself as its last action, the call is executed using the stack-frame of the caller.Example 6.6.1 Assume the following function which computes the sum of a vari-able number of arguments:------------------------------------------------------------------------------- 6.6 Function Applications79def sum(xs: Int*) = (0 /: xs) ((x, y) => x + y)Thensum(1, 2, 3, 4)sum(List(1, 2, 3, 4) : *)both yield 10 as result. On the other hand, sum(List(1, 2, 3, 4) )would not typecheck.6.6.1 Named and Default ArgumentsIf an application might uses named arguments p = e or default arguments, the fol-lowing conditions must hold. · The named arguments form a suffix of the argument list e1, ..., em, i.e. no po-sitional argument follows a named one.· The names xi of all named arguments are pairwise distinct and no named argument defines a parameter which is already specified by a positional argu-ment.· Every formal parameter p j : Tj which is not specified by either a positional ora named argument has a default argument. If the application uses named or default arguments the following transformation isapplied to convert it into an application without named or default arguments.If the function f has the form p.m[targs] it is transformed into the block { val q = pq.m[targs]}If the function f is itself an application expression the transformation is appliedrecursively on f . The result of transforming f is a block of the form { val q = pval x1 = expr1. . .val xk = exprkq.m[targs](args1) , ...,(argsl )}where every argument in (args1) , ..., (argsl ) is a reference to one of the values x1, ..., xk. To integrate the current application into the block, first a value definition-------------------------------------------------------------------------------80Expressions using a fresh name yi is created for every argument in e1, ..., em, which is initialisedto ei for positional arguments and to e for named arguments of the form x.ii = ei Then, for every parameter which is not specified by the argument list, a value defi-nition using a fresh name zi is created, which is initialized using the method com-puting the default argument of this parameter (§4.6) . Let args be a permutation of the generated names yi and zi such such that the po-sition of each name matches the position of its corresponding parameter in themethod type (p1 : T1, ..., pn : Tn) U . The final result of the transformation is a block of the form{ val q = pval x1 = expr1. . .val xl = exprkval y1 = e1. . .val ym = emval z1 = q.m$default$i[targs](args1) , ...,(argsl ) . . .val zd = q.m$default$j[targs](args1) , ...,(argsl )q.m[targs](args1) , ...,(argsl ) (args)}6.7Method ValuesSyntax:SimpleExpr ::=SimpleExpr1 `'The expression e _ is well-formed if e is of method type or if e is a call-by-nameparameter. If e is a method with parameters, e _ represents e converted to a func- tion type by eta expansion (§6.26.5) .If e is a parameterless method or call-by-nameparameter of type =>T , e _ represents the function of type () => T , which evalu-ates e when it is applied to the empty parameterlist () . Example 6.7.1 The method values in the left column are each equivalent to theanonymous functions (§6.23) on their right.Math.sin _x => Math.sin(x)Array.range _ (x1, x2) => Array.range(x1, x2)List.map2 _(x1, x2) => (x3) => List.map2(x1, x2) (x3)List.map2(xs, ys) _x => List.map2(xs, ys) (x)Note that a space is necessary between a method name and the trailing underscore -------------------------------------------------------------------------------6.8 Type Applications81because otherwise the underscore would be considered part of the name. 6.8Type ApplicationsSyntax:SimpleExpr::=SimpleExpr TypeArgsA type application e[T1, ..., Tn] instantiates a polymorphic value e of type[a1 >: L1 <: U1, . . . , an >: Ln <: Un]S with argument types T1, . . . , Tn. Every argument type Ti must obey the corresponding bounds Li and Ui . That is, foreach i = 1, ..., n, we must have Li <: Ti <: Ui , where is the substitution[a1 := T1, ..., an := Tn]. The type of the application is S. If the function part e is of some value type, the type application is taken to be equiv-alent to e.apply[T1, ..., Tn], i.e. the application of an apply method defined bye.Type applications can be omitted if local type inference (§6.26.4) can infer best type parameters for a polymorphic functions from the types of the actual function argu-ments and the expected result type.6.9TuplesSyntax:SimpleExpr::= `(' [Exprs] `) 'A tuple expression (e1, ..., en) is an alias for the class instance creationscala.Tuplen(e1, . . . , en) , where n 2. The empty tuple () is the unique value of type scala.Unit.6.10Instance Creation ExpressionsSyntax:SimpleExpr::=`new' (ClassTemplate | TemplateBody)A simple instance creation expression is of the form new c where c is a constructor invocation (§5.1.1) .Let T be the type of c. Then T must denote a (a type instanceof ) a non-abstract subclass of scala.AnyRef. Furthermore, the concrete self type ofthe expression must conform to the self type of the class denoted by T (§5.1) .The concrete self type is normally T , except if the expression new c appears as the righthand side of a value definition------------------------------------------------------------------------------- 82Expressionsval x: S = new c(where the type annotation : S may be missing) . In the latter case, the concreteself type of the expression is the compound type T with x.type. The expression is evaluated by creating a fresh object of type T which is is initializedby evaluating c. The type of the expression is T .A general instance creation expression is of the form new t for some class template t (§5.1) .Such an expression is equivalent to the block{ class a extends t ; new a }where a is a fresh name of an anonymous class which is inaccessible to user pro-grams.There is also a shorthand form for creating values of structural types: If {D} is a class body, then new {D} is equivalent to the general instance creation expressionnew AnyRef{D}.Example 6.10.1 Consider the following structural instance creation expression:new { def getName() = "aaron" } This is a shorthand for the general instance creation expressionnew AnyRef{ def getName() = "aaron" }The latter is in turn a shorthand for the block{ class anon$X extends AnyRef{ def getName() = "aaron" }; new anon$X } where anon$X is some freshly created name.6.11BlocksSyntax:BlockExpr::=`{' Block `}'Block::={BlockStat semi} [ResultExpr] A block expression {s1; ...; sn; e } is constructed from a sequence of block state-ments s1, ..., sn and a final expression e. The statement sequence may not containtwo definitions or declarations that bind the same name in the same namespace. The final expression can be omitted, in which case the unit value () is assumed.The expected type of the final expression e is the expected type of the block. Theexpected type of all preceding statements is undefined. -------------------------------------------------------------------------------6.12 Prefix, Infix, and Postfix Operations83The type of a block s1; ...; sn; e is T forSome {Q }, where T is the type of e and Q contains existential clauses (§3.2.10) for every value or type name which isfree in T and which is defined locally in one of the statements s1, ..., sn. We say theexistential clause binds the occurrence of the value or type name. Specifically, · A locally defined type definition type t = T is bound by the existential clausetype t >: T <: T . It is an error if t carries type parameters.· A locally defined value definition val x : T = e is bound by the existential clause val x : T .· A locally defined class definition class c extends t is bound by the existen-tial clause type c <: T where T is the least class type or refinement type whichis a proper supertype of the type c. It is an error if c carries type parameters. · A locally defined object definition object x extends t is bound by the existen-tial clause val x : T where T is the least class type or refinement type which isa proper supertype of the type x.type. Evaluation of the block entails evaluation of its statement sequence, followed by anevaluation of the final expression e, which defines the result of the block.Example 6.11.1 Assuming a class Ref[T](x: T) , the block { class C extends B {. . .} ; new Ref(new C) }has the type Ref[1] forSome { type 1 <: B }. The block{ class C extends B {. . .} ; new C }simply has type B, because with the rules in (§3.2.10the existentially quantified type 1 forSome { type 1 <: B } can be simplified to B.6.12Prefix, Infix, and Postfix OperationsSyntax:PostfixExpr::=InfixExpr [id [nl]]InfixExpr ::=PrefixExpr|InfixExpr id [nl] InfixExprPrefixExpr::=[`-' | `+' | `!' | `~'] SimpleExprExpressions can be constructed from operands and operators. -------------------------------------------------------------------------------84Expressions6.12.1 Prefix OperationsA prefix operation op e consists of a prefix operator op, which must be one of the identifiers `+', `-', `!' or `~'. The expression op e is equivalent to the postfix methodapplication e.unaryop.Prefix operators are different from normal function applications in that their operand expression need not be atomic. For instance, the input sequence -sin(x)is read as -(sin(x) ), whereas the function application negate sin(x) would beparsed as the application of the infix operator sin to the operands negate and (x) . 6.12.2 Postfix OperationsA postfix operator can be an arbitrary identifier. The postfix operation e op is inter-preted as e.op.6.12.3 Infix OperationsAn infix operator can be an arbitrary identifier. Infix operators have precedence and associativity defined as follows:The precedence of an infix operator is determined by the operator's first character.Characters are listed below in increasing order of precedence, with characters on the same line having the same precedence.(all letters)|^&< >= !:+ -* / %(all other special characters) That is, operators starting with a letter have lowest precedence, followed by opera-tors starting with `|', etc.There's one exception to this rule, which concerns assignment operators(§6.12.4) . The precedence of an assigment operator is the same as the one of simple assign-ment (=) . That is, it is lower than the precedence of any other operator.The associativity of an operator is determined by the operator's last character. Op- erators ending in a colon `:' are right-associative. All other operators are left-associative.Precedence and associativity of operators determine the grouping of parts of an ex-pression as follows. -------------------------------------------------------------------------------6.12 Prefix, Infix, and Postfix Operations85· If there are several infix operations in an expression, then operators with higher precedence bind more closely than operators with lower precedence.· If there are consecutive infix operations e0 op1 e1 op2 ...opn en with operatorsop1, ..., opn of the same precedence, then all these operators must have the same associativity. If all operators are left-associative, the sequence is inter-preted as (. . . (e0 op1 e1) op2 ...) opn en. Otherwise, if all operators are right-associative, the sequence is interpreted as e0 op1 (e1 op2 (...opn en) ...) . · Postfix operators always have lower precedence than infix operators. E.g.e1 op1 e2 op2 is always equivalent to (e1 op1 e2) op2.The right-hand operand of a left-associative operator may consist of several argu- ments enclosed in parentheses, e.g. e op (e1,...,en) . This expression is then inter-preted as e.op(e1,...,en) .A left-associative binary operation e1 op e2 is interpreted as e1.op(e2) . If op is right- associative, the same operation is interpreted as { val x=e1; e2.op(x ) }, wherex is a fresh name.6.12.4 Assignment OperatorsAn assignment operator is an operator symbol (syntax category op in (§1.1) )that ends in an equals character "=", with the exception of operators for which one of thefollowing conditions holds:(1) the operator also starts with an equals character, or(2) the operator is one of (<=) , (>=) , (!=) . Assignment operators are treated specially in that they can be expanded to assign-ments if no other interpretation is valid.Let's consider an assignment operator such as += in an infix operation l += r , where l , r are expressions. This operation can be re-interpreted as an operationwhich corresponds to the assignmentl = l + rexcept that the operation's left-hand-side l is evaluated only once. The re-interpretation occurs if the following two conditions are fulfilled.1. The left-hand-side l does not have a member named +=, and also cannot beconverted by an implicit conversion (§6.26) to a value with a member named +=.2. The assignment l = l + r is type-correct. In particular this implies that lrefers to a variable or object that can be assigned to, and that is convertibleto a value with a member named +. -------------------------------------------------------------------------------86Expressions6.13Typed ExpressionsSyntax:Expr1::= PostfixExpr `:' CompoundTypeThe typed expression e : T has type T . The type of expression e is expected to con-form to T . The result of the expression is the value of e converted to type T . Example 6.13.1 Here are examples of well-typed and illegally typed expressions.1: Int// legal, of type Int1: Long// legal, of type Long// 1: string// ***** illegal 6.14Annotated ExpressionsSyntax:Expr1::=PostfixExpr `:' Annotation {Annotation}An annotated expression e: @a1 ... @an attaches annotations a1, ..., an to the ex- pression e (§11) .6.15AssignmentsSyntax:Expr1::=[SimpleExpr `.'] id `=' Expr|SimpleExpr1 ArgumentExprs `=' Expr The interpretation of an assignment to a simple variable x = e depends on thedefinition of x. If x denotes a mutable variable, then the assignment changes thecurrent value of x to be the result of evaluating the expression e. The type of e is expected to conform to the type of x. If x is a parameterless function defined insome template, and the same template contains a setter function x= as member,then the assignment x = e is interpreted as the invocation x=(e ) of that setter function. Analogously, an assignment f .x = e to a parameterless function x isinterpreted as the invocation f .x=(e ) .An assignment f (args ) = e with a function application to the left of the `=' oper- ator is interpreted as f .update(args, e ) , i.e. the invocation of an update functiondefined by f .-------------------------------------------------------------------------------6.15 Assignments 87Example 6.15.1 Here are some assignment expressions and their equivalent ex-pansions.x.f = ex.f=(e)x.f() = ex.f.update(e)x.f(i) = e x.f.update(i, e)x.f(i, j) = ex.f.update(i, j, e)Example 6.15.2 Here is the usual imperative code for matrix multiplication.def matmul(xss: Array[Array[Double]], yss: Array[Array[Double]]) = { val zss: Array[Array[Double]] = new Array(xss.length, yss(0) .length)var i = 0while (i < xss.length) {var j = 0while (j < yss(0) .length) {var acc = 0.0 var k = 0while (k < yss.length) {acc = acc + xss(i) (k) * yss(k) (j)k += 1}zss(i) (j) = accj += 1}i += 1} zss}Desugaring the array accesses and assignments yields the following expanded ver-sion:def matmul(xss: Array[Array[Double]], yss: Array[Array[Double]]) = {val zss: Array[Array[Double]] = new Array(xss.length, yss.apply(0) .length) var i = 0while (i < xss.length) {var j = 0while (j < yss.apply(0) .length) {var acc = 0.0var k = 0while (k < yss.length) {acc = acc + xss.apply(i) .apply(k) * yss.apply(k) .apply(j) k += 1}zss.apply(i) .update(j, acc)j += 1-------------------------------------------------------------------------------88Expressions} i += 1}zss}6.16Conditional ExpressionsSyntax:Expr1::=`if' `(' Expr `) ' {nl} Expr [[semi] `else' Expr] The conditional expression if (e1) e2 else e3 chooses one of the values of e2and e3, depending on the value of e1. The condition e1 is expected to conform totype Boolean. The then-part e2 and the else-part e3 are both expected to conform to the expected type of the conditional expression. The type of the conditional expres-sion is the weak least upper bound (§3.5.3) of the types of e2 and e3. A semicolonpreceding the else symbol of a conditional expression is ignored. The conditional expression is evaluated by evaluating first e1. If this evaluates totrue, the result of evaluating e2 is returned, otherwise the result of evaluating e3 isreturned.A short form of the conditional expression eliminates the else-part. The conditional expression if (e1) e2 is evaluated as if it was if (e1) e2 else () .6.17While Loop ExpressionsSyntax:Expr1::=`while' `(' Expr ') ' {nl} Expr The while loop expression while (e1) e2 is typed and evaluated as if it was anapplication of whileLoop (e1) (e2) where the hypothetical function whileLoop isdefined as follows.def whileLoop(cond: => Boolean) (body: => Unit) : Unit =if (cond) { body ; whileLoop(cond) (body) } else {}6.18Do Loop ExpressionsSyntax:------------------------------------------------------------------------------- 6.19 For Comprehensions and For Loops89Expr1::=`do' Expr [semi] `while' `(' Expr ') 'The do loop expression do e1 while (e2) is typed and evaluated as if it was the expression (e1 ; while (e2) e1) . A semicolon preceding the while symbol of ado loop expression is ignored.6.19For Comprehensions and For LoopsSyntax:Expr1 ::=`for' (`(' Enumerators `) ' | `{' Enumerators `}'){nl} [`yield'] ExprEnumerators::=Generator {semi Enumerator}Enumerator ::=Generator|Guard|`val' Pattern1 `=' ExprGenerator::=Pattern1 `<-' Expr [Guard]Guard::= `if' PostfixExprA for loop for (enums ) e executes expression e for each binding generated bythe enumerators enums. A for comprehension for (enums ) yield e evaluatesexpression e for each binding generated by the enumerators enums and collects the results. An enumerator sequence always starts with a generator; this can be fol-lowed by further generators, value definitions, or guards. A generator p <- e pro-duces bindings from an expression e which is matched in some way against pat- tern p. A value definition p = e binds the value name p (or several names in apattern p) to the result of evaluating the expression e. A guard if e contains aboolean expression which restricts enumerated bindings. The precise meaning of generators and guards is defined by translation to invocations of four methods: map,withFilter, flatMap, and foreach. These methods can be implemented in differentways for different carrier types. The translation scheme is as follows. In a first step, every generator p <- e, wherep is not irrefutable (§8.1) for the type of e is replaced byp <- e.withFilter { case p => true; case _ => false } Then, the following rules are applied repeatedly until all comprehensions have beeneliminated.· Aforcomprehensionfor (p <- e ) yield eis translatedtoe.map { case p => e }.· A for loop for (p <- e ) e is translated to e.foreach { case p => e }.· A for comprehension------------------------------------------------------------------------------- 90Expressionsfor (p <- e; p <- e . . .) yield e,where . . . is a (possibly empty) sequence of generators, definitions, or guards,is translated to e.flatMap { case p => for (p <- e . . .) yield e} .· A for loopfor (p <- e; p <- e . . .) e.where . . . is a (possibly empty) sequence of generators, definitions, or guards, is translated toe.foreach { case p => for (p <- e . . .) e} .· A generator p <- e followed by a guard if g is translated to a single gen-erator p <- e.withFilter((x1, ..., xn) => g ) where x1, ..., xn are the free variables of p.· A generator p <- e followed by a value definition p = e is translated to thefollowing generator of pairs of values, where x and x are fresh names:(p, p ) <- for (x@p <- e) yield { val x @p = e ; (x, x ) } Example 6.19.1 The following code produces all pairs of numbers between 1 andn - 1 whose sums are prime.for{ i <- 1 until nj <- 1 until iif isPrime(i+j) } yield (i, j)The for comprehension is translated to:(1 until n).flatMap {case i => (1 until i).withFilter { j => isPrime(i+j) }.map { case j => (i, j) } } Example 6.19.2 For comprehensions can be used to express vector and matrix al-gorithms concisely. For instance, here is a function to compute the transpose of agiven matrix:def transpose[A](xss: Array[Array[A]]) = { for (i <- Array.range(0, xss(0) .length) ) yield-------------------------------------------------------------------------------6.20 Return Expressions91for (xs <- xss) yield xs(i) }Here is a function to compute the scalar product of two vectors:def scalprod(xs: Array[Double], ys: Array[Double]) = {var acc = 0.0for ((x, y) <- xs zip ys) acc = acc + x * y acc}Finally, here is a function to compute the product of two matrices. Compare withthe imperative version of Example 6.15.2.def matmul(xss: Array[Array[Double]], yss: Array[Array[Double]]) = { val ysst = transpose(yss)for (xs <- xss) yieldfor (yst <- ysst) yieldscalprod(xs, yst)}The code above makes use of the fact that map, flatMap, withFilter, and foreach are defined for instances of class scala.Array.6.20Return ExpressionsSyntax:Expr1::=`return' [Expr]A return expression return e must occur inside the body of some enclosing named method or function. The innermost enclosing named method or function in asource program, f , must have an explicitly declared result type, and the type of emust conform to it. The return expression evaluates the expression e and returns its value as the result of f . The evaluation of any statements or expressions followingthe return expression is omitted. The type of a return expression is scala.Nothing.The expression e may be omitted. The return expression return is type-checked and evaluated as if it was return () .An apply method which is generated by the compiler as an expansion of an anony-mous function does not count as a named function in the source program, and therefore is never the target of a return expression.Returning from a nested anonymous function is implemented by throwing andcatching a scala.runtime.NonLocalReturnControl.Any exception catches be- tween the point of return and the enclosing methods might see the exception. A-------------------------------------------------------------------------------92Expressionskey comparison makes sure that these exceptions are only caught by the method instance which is terminated by the return.If the return expression is itself part of an anonymous function, it is possible thatthe enclosing instance of f has already returned before the return expression is ex- ecuted. In that case, the thrown scala.runtime.NonLocalReturnControl will notbe caught, and will propagate up the call stack.6.21Throw ExpressionsSyntax:Expr1 ::=`throw' ExprA throw expression throw e evaluates the expression e. The type of this expressionmust conform to Throwable. If e evaluates to an exception reference, evaluation is aborted with the thrown exception. If e evaluates to null, evaluation is insteadaborted with a NullPointerException. If there is an active try expression (§6.22)which handles the thrown exception, evaluation resumes with the handler; other- wise the thread executing the throw is aborted. The type of a throw expression isscala.Nothing.6.22Try ExpressionsSyntax:Expr1 ::=`try' `{' Block `}' [`catch' `{' CaseClauses `}'] [`finally' Expr]A try expression is of the form try { b } catch h where the handler h is a patternmatching anonymous function (§8.5){ case p1 => b1 . . . case pn => bn } . This expression is evaluated by evaluating the block b. If evaluation of b does notcause an exception to be thrown, the result of b is returned. Otherwise the handlerh is applied to the thrown exception. If the handler contains a case matching the thrown exception, the first such case is invoked. If the handler contains no casematching the thrown exception, the exception is re-thrown.Let pt be the expected type of the try expression. The block b is ex-pected to conform to pt.The handler h is expected conform to typescala.PartialFunction[scala.Throwable, pt ]. The type of the try expression isthe weak least upper bound (§3.5.3) of the type of b and the result type of h. -------------------------------------------------------------------------------6.23 Anonymous Functions93A try expression try { b } finally e evaluates the block b. If evaluation of b does not cause an exception to be thrown, the expression e is evaluated. If an excep-tion is thrown during evaluation of e, the evaluation of the try expression is abortedwith the thrown exception. If no exception is thrown during evaluation of e, the result of b is returned as the result of the try expression.If an exception is thrown during evaluation of b, the finally block e is also evalu-ated. If another exception e is thrown during evaluation of e, evaluation of the try expression is aborted with the thrown exception. If no exception is thrown duringevaluation of e, the original exception thrown in b is re-thrown once evaluation of ehas completed. The block b is expected to conform to the expected type of the try expression. The finally expression e is expected to conform to type Unit.A try expressiontry { b } catch e1 finally e2is a shorthand fortry { try { b } catch e1 } finally e2. 6.23Anonymous FunctionsSyntax:Expr::=(Bindings | [`implicit'] id | `') `=>' ExprResultExpr::=(Bindings | ([`implicit'] id | `') `:' CompoundType) `=>' Block Bindings::=`(' Binding {`,' Binding} `) 'Binding::=(id | `') [`:' Type]The anonymous function (x1: T1, ..., xn: Tn) => e maps parameters xi of types Ti to a result given by expression e. The scope of each formal parameter xi is e.Formal parameters must have pairwise distinct names.Iftheexpectedtype oftheanonymousfunctionisoftheformscala.Functionn[S1, . . . , Sn, R ], the expected type of e is R and the type Tiof any of the parameters xi can be omitted, in which case Ti = Si is assumed. If the expected type of the anonymous function is some other type, all formal parametertypes must be explicitly given, and the expected type of e is undefined. The typeof the anonymous function is scala.Functionn[S1, ..., Sn, T ], where T is the packed type (§6.1) of e. T must be equivalent to a type which does not refer to anyof the formal parameters xi .The anonymous function is evaluated as the instance creation expression new scala.Functionn[T1, . . . , Tn, T ] {def apply(x1: T1, . . . , xn: Tn) : T = e}In the case of a single untyped formal parameter, (x ) => e can be abbreviated tox => e. If an anonymous function (x: T ) => e with a single typed parameter appears as the result expression of a block, it can be abbreviated to x: T => e.-------------------------------------------------------------------------------94Expressions A formal parameter may also be a wildcard represented by an underscore . In thatcase, a fresh name for the parameter is chosen arbitrarily.A named parameter of an anonymous function may be optionally preceded by an implicit modifier. In that case the parameter is labeled implicit (§7) ;howeverthe parameter section itself does not count as an implicit parameter section in thesense of (§7.2) .Hence, arguments to anonymous functions always have to be given explicitly.Example 6.23.1 Examples of anonymous functions:x => x// The identity functionf => g => x => f(g(x) )// Curried function composition (x: Int,y: Int) => x + y// A summation function() => { count += 1; count }// The function which takes an// empty parameter list () ,// increments a non-local variable // `count' and returns the new value._ => 5// The function that ignores its argument// and always returns 5.Placeholder Syntax for Anonymous FunctionsSyntax: SimpleExpr1::=`'An expression (of syntactic category Expr) may contain embedded underscore sym-bols _ at places where identifiers are legal. Such an expression represents an anony- mous function where subsequent occurrences of underscores denote successiveparameters.Define an underscore section to be an expression of the form :T where T is a type,or else of the form , provided the underscore does not appear as the expression part of a type ascription :T .An expression e of syntactic category Expr binds an underscore section u, if the fol-lowing two conditions hold: (1) e properly contains u, and (2) there is no other ex- pression of syntactic category Expr which is properly contained in e and which itselfproperly contains u.If an expression e binds underscore sections u1, ..., un, in this order, it is equivalent to the anonymous function (u , ... uresults from u1n ) => ewhere each uii byreplacing the underscore with a fresh identifier and e results from e by replacing -------------------------------------------------------------------------------6.24 Constant Expressions95each underscore section ui by u .iExample 6.23.2 The anonymous functions in the left column use placeholder syn- tax. Each of these is equivalent to the anonymous function on its right._ + 1x => x + 1_ * _(x1, x2) => x1 * x2(: Int) * 2(x: Int) => (x: Int) * 2 if () x else yz => if (z) x else y.map(f)x => x.map(f).map(_ + 1)x => x.map(y => y + 1)6.24Constant ExpressionsConstant expressions are expressions that the Scala compiler can evaluate to a con- stant. The definition of "constant expression" depends on the platform, but theyinclude at least the expressions of the following forms:· A literal of a value class, such as an integer · A string literal· A class constructed with Predef.classOf (§12.5)· An element of an enumeration from the underlying platform· A literal array, of the form Array(c1, ..., cn) , where all of the ci 's are themselves constant expressions· An identifier defined by a constant value definition (§4.1) .6.25StatementsSyntax:BlockStat::=Import| {Annotation} [`implicit'] Def|{Annotation} {LocalModifier} TmplDef|Expr1|TemplateStat ::=Import|{Annotation} {Modifier} Def |{Annotation} {Modifier} Dcl|Expr|-------------------------------------------------------------------------------96ExpressionsStatements occur as parts of blocks and templates. A statement can be an import, a definition or an expression, or it can be empty. Statements used in the templateof a class definition can also be declarations. An expression that is used as a state-ment can have an arbitrary value type. An expression statement e is evaluated by evaluating e and discarding the result of the evaluation.Block statements may be definitions which bind local names in the block. The onlymodifier allowed in all block-local definitions is implicit. When prefixing a class or object definition, modifiers abstract, final, and sealed are also permitted.Evaluation of a statement sequence entails evaluation of the statements in the orderthey are written.6.26 Implicit ConversionsImplicit conversions can be applied to expressions whose type does not match theirexpected type, to qualifiers in selections, and to unapplied methods. The available implicit conversions are given in the next two sub-sections.We say, a type T is compatible to a type U if T conforms to U after applying eta-expansion (§6.26.5) and view applications (§7.3) . 6.26.1 Value ConversionsThe following five implicit conversions can be applied to an expression e which hassome value type T and which is type-checked with some expected type pt.Overloading Resolution. If an expression denotes several possible members of aclass, overloading resolution (§6.26.3) is applied to pick a unique member.Type Instantiation.An expression e of polymorphic type [a1 >: L1 <: U1, . . . , an >: Ln <: Un]Twhich does not appear as the function part of a type application is converted to atype instance of T by determining with local type inference (§6.26.4) instance types T1, ..., Tn for the type variables a1, ..., an and implicitly embedding e in the typeapplication e[T1, ..., Tn] (§6.8) .Numeric Widening.If e has a primitive number type which weakly conforms (§3.5.3) to the expected type, it is widened to the expected type using one of thenumeric conversion methods toShort, toChar, toInt, toLong, toFloat, toDoubledefined in §12.2.1.------------------------------------------------------------------------------- 6.26 Implicit Conversions97Numeric Literal Narrowing.If the expected type is Byte, Short or Char, and theexpression e is an integer literal fitting in the range of that type, it is converted to the same literal in that type.Value Discarding.If e has some value type and the expected type is Unit, e is con-verted to the expected type by embedding it in the term { e; () }. View Application.If none of the previous conversions applies, and e's type doesnot conform to the expected type pt, it is attempted to convert e to the expectedtype with a view (§7.3) . Dynamic Member Selection.If none of the previous conversions applies, and e isa prefix of a selection e.x, and e's type conforms to class scala.Dynamic, then theselection is rewritten according to the rules for dynamic member selection (§??) . 6.26.2 Method ConversionsThe following four implicit conversions can be applied to methods which are notapplied to some argument list.Evaluation.A parameterless method m of type => T is always converted to type T by evaluating the expression to which m is bound.Implicit Application.If the method takes only implicit parameters, implicit argu-ments are passed following the rules of §7.2. Eta Expansion.Otherwise, if the method is not a constructor, and the expectedtype pt is a function type (Ts ) T , eta-expansion (§6.26.5) is performed on theexpression e.Empty Application. Otherwise, if e has method type () T , it is implicitly applied tothe empty argument list, yielding e() .6.26.3 Overloading ResolutionIf an identifier or selection e references several members of a class, the context of the reference is used to identify a unique member. The way this is done depends onwhether or not e is used as a function. Let A be the set of members referenced by e.Assume first that e appears as a function in an application, as in e(e1, ..., em) . -------------------------------------------------------------------------------98ExpressionsOne first determines the set of functions that is potentially applicable based on the shape of the arguments.The shape of an argument expression e, written shape(e) , is a type that is defined asfollows:· Forafunctionexpression (p1: T1, . . . , pn: Tn) => b:(Any , . . . , Any) => shape(b) , where Any occurs n times in the argumenttype.· For a named argument n = e: shape(e) .· For all other expressions: Nothing. Let B be the set of alternatives in A that are applicable (§6.6) to expressions(e1, ..., en) of types (shape(e1) , ..., shape(en) ). If there is precisely one alternativein B, that alternative is chosen. Otherwise, let S1, ..., Sm be the vector of types obtained by typing each argumentwith an undefined expected type. For every member m in B one determineswhether it is applicable to expressions (e1, ..., em) of types S1, ..., Sm. It is an error if none of the members in B is applicable. If there is one single applicable alterna-tive, that alternative is chosen. Otherwise, let C be the set of applicable alternativeswhich don't employ any default argument in the application to e1, ..., em. It is again an error if C is empty. Otherwise, one chooses the most specific alternative amongthe alternatives in C , according to the following definition of being "as specific as",and "more specific than": · A parameterized method m of type (p1 : T1, ..., pn : Tn) U is as specific as someother member m of type S if m is applicable to arguments (p1, ..., pn ) oftypes T1, ..., Tn.· A polymorphic method of type [a1 >: L1 <: U1, ..., an >: Ln <: Un]T is as specific as some other member of type S if T is as specific as S under theassumption that for i = 1, ..., n each ai is an abstract type name boundedfrom below by Li and from above by Ui . · A member of any other type is always as specific as a parameterized methodor a polymorphic method.· Given two members of types T and U which are neither param-eterized nor polymorphic method types, the member of type T is as specific as the member of type U if the existential dual of Tconforms to the existential dual of U .Here, the existential dualof a polymorphic type[a1 >: L1 <: U1, . . . , an >: Ln <: Un]T isT forSome { type a1 >: L1 <: U1 , ..., type an >: Ln <: Un}. The ex-istential dual of every other type is the type itself.------------------------------------------------------------------------------- 6.26 Implicit Conversions99The relative weight of an alternative A over an alternative B is a number from 0 to 2,defined as the sum of· 1 if A is as specific as B , 0 otherwise, and · 1 if A is defined in a class or object which is derived from the class or objectdefining B , 0 otherwise.A class or object C is derived from a class or object D if one of the following holds: · C is a subclass of D, or· C is a companion object of a class derived from D, or· D is a companion object of a class from which C is derived.An alternative A is more specific than an alternative B if the relative weight of A over B is greater than the relative weight of B over A.It is an error if there is no alternative in C which is more specific than all otheralternatives in C .Assume next that e appears as a function in a type application, as in e[targs ]. Then all alternatives in A which take the same number of type parameters as there aretype arguments in targs are chosen. It is an error if no such alternative exists. Ifthere are several such alternatives, overloading resolution is applied again to the whole expression e[targs ].Assume finally that e does not appear as a function in either an application or a typeapplication. If an expected type is given, let B be the set of those alternatives in A which are compatible (§6.26) to it. Otherwise, let B be the same as A . We choosein this case the most specific alternative among all alternatives in B. It is an error ifthere is no alternative in B which is more specific than all other alternatives in B. Example 6.26.1 Consider the following definitions:class A extends B {}def f(x: B, y: B) = . . .def f(x: A, y: B) = . . .val a: Aval b: BThen the application f(b, b) refers to the first definition of f whereas the applica- tion f(a, a) refers to the second. Assume now we add a third overloaded definitiondef f(x: B, y: A) = . . .Then the application f(a, a) is rejected for being ambiguous, since no most spe- cific applicable signature exists.-------------------------------------------------------------------------------100Expressions6.26.4 Local Type InferenceLocal type inference infers type arguments to be passed to expressions of polymor- phic type. Say e is of type [a1 >: L1 <: U1, ..., an >: Ln <: Un]T and no explicit typeparameters are given.Local type inference converts this expression to a type application e[T1, ..., Tn]. The choice of the type arguments T1, ..., Tn depends on the context in which theexpression appears and on the expected type pt. There are three cases.Case 1: Selections.If the expression appears as the prefix of a selection with a name x, then type inference is deferred to the whole expression e.x. That is, if e.xhas type S, it is now treated as having type [a1 >: L1 <: U1, ..., an >: Ln <: Un]S, andlocal type inference is applied in turn to infer type arguments for a1, ..., an, using the context in which e.x appears.Case 2: Values.If the expression e appears as a value without being applied tovalue arguments, the type arguments are inferred by solving a constraint system which relates the expression's type T with the expected type pt. Without loss ofgenerality we can assume that T is a value type; if it is a method type we applyeta-expansion (§6.26.5) to convert it to a function type. Solving means finding a substitution of types Ti for the type parameters ai such that· None of inferred types Ti is a singleton type §3.2.1· All type parameter bounds are respected, i.e. Li <: ai and ai <: Ui for i = 1, ..., n.· The expression's type conforms to the expected type, i.e. T <: pt.It is a compile time error if no such substitution exists. If several substitutions exist,local-type inference will choose for each type variable ai a minimal or maximal type Ti of the solution space. A maximal type Ti will be chosen if the type parameter aiappears contravariantly (§4.5) in the type T of the expression. A minimal type Tiwill be chosen in all other situations, i.e. if the variable appears covariantly, non- variantly or not at all in the type T . We call such a substitution an optimal solutionof the given constraint system for the type T .Case 3: Methods.The last case applies if the expression e appears in an applica- tion e(d1, ..., dm) . In that case T is a method type (p1 : R1, ..., pm : Rm) T . With-out loss of generality we can assume that the result type T is a value type; if it is amethod type we apply eta-expansion (§6.26.5) to convert it to a function type. One computes first the types S j of the argument expressions d j , using two alternativeschemes. Each argument expression d j is typed first with the expected type R j , inwhich the type parameters a1, ..., an are taken as type constants. If this fails, the -------------------------------------------------------------------------------6.26 Implicit Conversions101argument d j is typed instead with an expected type R which results from R jj byreplacing every type parameter in a1, ..., an with undefined.In a second step, type arguments are inferred by solving a constraint systemwhich relates the method's type with the expected type pt and the argument types S1, ..., Sm. Solving the constraint system means finding a substitution of types Tifor the type parameters ai such that· None of inferred types Ti is a singleton type §3.2.1· All type parameter bounds are respected, i.e. Li <: ai and ai <: Ui for i = 1, ..., n.· The method's result type T conforms to the expected type, i.e. T <: pt.· Each argument type weakly conforms (§3.5.3) to the corresponding formalparameter type, i.e. S j <:w R j for j = 1, ..., m. It is a compile time error if no such substitution exists. If several solutions exist, anoptimal one for the type T is chosen.All or parts of an expected type pt may be undefined. The rules for conformance (§3.5.2) are extended to this case by adding the rule that for any type T the followingtwo statements are always true:undefined <: TandT <: undefined.It is possible that no minimal or maximal solution for a type variable exists, in which case a compile-time error results. Because <: is a pre-order, it is also possible that asolution set has several optimal solutions for a type. In that case, a Scala compiler isfree to pick any one of them. Example 6.26.2 Consider the two methods:def cons[A](x: A, xs: List[A]) : List[A] = x :: xsdef nil[B]: List[B] = Niland the definitionval xs = cons(1, nil) .The application of cons is typed with an undefined expected type. This application is completed by local type inference to cons[Int](1, nil) . Here, one uses thefollowing reasoning to infer the type argument Int for the type parameter a:First, the argument expressions are typed. The first argument 1 has type Int whereas the second argument nil is itself polymorphic. One tries to type-checknil with an expected type List[a]. This leads to the constraint systemList[b?] <: List[a]------------------------------------------------------------------------------- 102Expressionswhere we have labeled b? with a question mark to indicate that it is a variable inthe constraint system. Because class List is covariant, the optimal solution of this constraint isb = scala.Nothing .In a second step, one solves the following constraint system for the type parametera of cons:Int <: a?List[scala.Nothing] <: List[a?] List[a?] <: undefinedThe optimal solution of this constraint system isa = Int ,so Int is the type inferred for a.Example 6.26.3 Consider now the definitionval ys = cons("abc", xs) where xs is defined of type List[Int] as before. In this case local type inferenceproceeds as follows.First, the argument expressions are typed. The first argument "abc" has type String.The second argument xs is first tried to be typed with expected typeList[a]. This fails, as List[Int] is not a subtype of List[a]. Therefore, the sec-ond strategy is tried; xs is now typed with expected type List[undefined]. This succeeds and yields the argument type List[Int].In a second step, one solves the following constraint system for the type parametera of cons:String <: a?List[Int] <: List[a?] List[a?] <: undefinedThe optimal solution of this constraint system isa = scala.Any ,so scala.Any is the type inferred for a.6.26.5 Eta ExpansionEta-expansion converts an expression of method type to an equivalent expression of function type. It proceeds in two steps.-------------------------------------------------------------------------------6.26 Implicit Conversions103First, one identifes the maximal sub-expressions of e; let's say these are e1, ..., em. For each of these, one creates a fresh name xi . Let e be the expression resultingfrom replacing every maximal subexpression ei in e by the corresponding freshname xi . Second, one creates a fresh name yi for every argument type Ti of the method (i = 1, ..., n) . The result of eta-conversion is then:{ val x1 = e1;. . .val xm = em;(y1 : T1, . . . , yn : Tn) => e (y1, . . . , yn)}------------------------------------------------------------------------------- -------------------------------------------------------------------------------Chapter 7Implicit Parameters and Views7.1The Implicit ModifierSyntax:LocalModifier ::= `implicit'ParamClauses::= {ParamClause} [nl] `(' `implicit' Params `) 'Template members and parameters labeled with an implicit modifier can bepassed to implicit parameters (§7.2) and can be used as implicit conversions called views (§7.3) .The implicit modifier is illegal for all type members, as well as fortop-level (§9.2) objects.Example 7.1.1 The following code defines an abstract class of monoids and two concrete implementations, StringMonoid and IntMonoid. The two implementa-tions are marked implicit.abstract class Monoid[A] extends SemiGroup[A] {def unit: Adef add(x: A, y: A) : A }object Monoids {implicit object stringMonoid extends Monoid[String] {def add(x: String, y: String) : String = x.concat(y)def unit: String = ""} implicit object intMonoid extends Monoid[Int] {def add(x: Int, y: Int) : Int = x + ydef unit: Int = 0}}------------------------------------------------------------------------------- 106Implicit Parameters and Views7.2Implicit ParametersAn implicit parameter list (implicit p1,...,pn) of a method marks the param-eters p1, ..., pn as implicit. A method or constructor can have only one implicit parameter list, and it must be the last parameter list given.A method with implicit parameters can be applied to arguments just like a normalmethod. In this case the implicit label has no effect. However, if such a method misses arguments for its implicit parameters, such arguments will be automaticallyprovided.The actual arguments that are eligible to be passed to an implicit parameter of typeT fall into two categories. First, eligible are all identifiers x that can be accessed at the point of the method call without a prefix and that denote an implicit definition(§7.1) or an implicit parameter. An eligible identifier may thus be a local name, or amember of an enclosing template, or it may be have been made accessible without a prefix through an import clause (§4.7) .If there are no eligible identifiers underthis rule, then, second, eligible are also all implicit members of some object thatbelongs to the implicit scope of the implicit parameter's type, T . The implicit scope of a type T consists of all companion modules (§5.4) of classesthat are associated with the implicit parameter's type. Here, we say a class C is asso-ciated with a type T , if it is a base class (§5.1.2) of some part of T . The parts of a type T are:· if T is a compound type T1 with ... with Tn, the union of the parts ofT1, ..., Tn, as well as T itself,· if T is a parameterized type S[T1, ..., Tn], the union of the parts of S and T1, ..., Tn,· if T is a singleton type p.type, the parts of the type of p,· if T is a type projection S#U , the parts of S as well as T itself,· in all other cases, just T itself. If there are several eligible arguments which match the implicit parameter's type,a most specific one will be chosen using the rules of static overloading resolution(§6.26.3) .If the parameter has a default argument and no implicit argument can be found the default argument is used.Example 7.2.1 Assuming the classes from Example 7.1.1,here is a method whichcomputes the sum of a list of elements using the monoid's add and unit operations. def sum[A](xs: List[A]) (implicit m: Monoid[A]) : A =if (xs.isEmpty) m.unitelse m.add(xs.head, sum(xs.tail) )------------------------------------------------------------------------------- 7.2 Implicit Parameters107The monoid in question is marked as an implicit parameter, and can therefore beinferred based on the type of the list. Consider for instance the call sum(List(1, 2, 3) )in a context where stringMonoid and intMonoid are visible. We know that the formaltype parameter a of sum needs to be instantiated to Int. The only eligible objectwhich matches the implicit formal parameter type Monoid[Int] is intMonoid so this object will be passed as implicit parameter.This discussion also shows that implicit parameters are inferred after any type ar-guments are inferred (§6.26.4) .Implicit methods can themselves have implicit parameters. An example is the fol- lowing method from module scala.List, which injects lists into the scala.Orderedclass, provided the element type of the list is also convertible to this type.implicit def list2ordered[A](x: List[A]) (implicit elem2ordered: A => Ordered[A]) : Ordered[List[A]] =...Assume in addition a methodimplicit def int2ordered(x: Int) : Ordered[Int]that injects integers into the Ordered class. We can now define a sort method over ordered lists:def sort[A](xs: List[A]) (implicit a2ordered: A => Ordered[A]) = ...We can apply sort to a list of lists of integers yss: List[List[Int]] as follows:sort(yss) The call above will be completed by passing two nested implicit arguments:sort(yss) (xs: List[Int] => list2ordered[Int](xs) (int2ordered) ) .The possibility of passing implicit arguments to implicit arguments raises the pos- sibility of an infinite recursion. For instance, one might try to define the followingmethod, which injects every type into the Ordered class:implicit def magic[A](x: A) (implicit a2ordered: A => Ordered[A]) : Ordered[A] = a2ordered(x)Now, if one tried to apply sort to an argument arg of a type that did not have an-other injection into the Ordered class, one would obtain an infinite expansion:sort(arg) (x => magic(x) (x => magic(x) (x => ... ) )) -------------------------------------------------------------------------------108Implicit Parameters and ViewsTo prevent such infinite expansions, the compiler keeps track of a stack of "open implicit types" for which implicit arguments are currently being searched. When-ever an implicit argument for type T is searched, the "core type" of T is added to thestack. Here, the core type of T is T with aliases expanded, top-level type annotations (§11) and refinements (§3.2.7) removed, and occurrences of top-level existentiallybound variables replaced by their upper bounds. The core type is removed from thestack once the search for the implicit argument either definitely fails or succeeds. Everytime a core type is added to the stack, it is checked that this type does notdominate any of the other types in the set.Here, a core type T dominates a type U if T is equivalent (§3.5.1) to U , or if the top- level type constructors of T and U have a common element and T is more complexthan U .The set of top-level type constructors ttcs(T ) of a type T depends on the form of thetype: For a type designator,ttcs(p.c) = {c};For a parameterized type,ttcs(p.c[targs]) = {c};For a singleton type,ttcs(p.t y pe) = ttcs(T ) , provided p has type T ; For a compound type,ttcs(T1 with ... with Tn) = ttcs(T1) ... ttcs(Tn) .The complexity complexity(T ) of a core type is an integer which also depends on theform of the type: For a type designator,complexity(p.c) = 1 + complexity(p)For a parameterized type,complexity(p.c[targs]) = 1 + complexity(targs)For a singleton type denoting a package p, complexity(p.t y pe) = 0For any other singleton type,complexity(p.t y pe) = 1 + complexity(T ) , provided p has type T ;For a compound type,complexity(T1 with ... with Tn) = complexity(Ti ) Example 7.2.2 Whentypingsort(xs)forsomelistxsoftypeList[List[List[Int]]], the sequence of types for which implicit arguments are searched isList[List[Int]] => Ordered[List[List[Int]]],List[Int] => Ordered[List[Int]]Int => Ordered[Int]------------------------------------------------------------------------------- 7.3 Views109All types share the common type constructor scala.Function1, but the complexityof the each new type is lower than the complexity of the previous types. Hence, the code typechecks.Example 7.2.3 Let ys be a list of some type which cannot be converted to Ordered.For instance:val ys = List(new IllegalArgumentException, new ClassCastException, new Error) Assume that the definition of magic above is in scope. Then the sequence of typesfor which implicit arguments are searched isThrowable => Ordered[Throwable],Throwable => Ordered[Throwable], ...Since the second type in the sequence is equal to the first, the compiler will issue anerror signalling a divergent implicit expansion.7.3ViewsImplicit parameters and methods can also define implicit conversions called views. A view from type S to type T is defined by an implicit value which has function typeS=>T or (=>S) =>T or by a method convertible to a value of that type.Views are applied in three situations. 1. If an expression e is of type T , and T does not conform to the expression'sexpected type pt. In this case an implicit v is searched which is applicable toe and whose result type conforms to pt. The search proceeds as in the case of implicit parameters, where the implicit scope is the one of T => pt. If such aview is found, the expression e is converted to v(e) .2. In a selection e.m with e of type T , if the selector m does not denote a member of T . In this case, a view v is searched which is applicable to e and whose resultcontains a member named m. The search proceeds as in the case of implicitparameters, where the implicit scope is the one of T . If such a view is found, the selection e.m is converted to v(e) .m.3. In a selection e.m(args) with e of type T , if the selector m denotes some mem-ber(s) of T , but none of these members is applicable to the arguments args. In this case a view v is searched which is applicable to e and whose result con-tains a method m which is applicable to args. The search proceeds as in thecase of implicit parameters, where the implicit scope is the one of T . If such a view is found, the selection e.m is converted to v(e) .m(args) .-------------------------------------------------------------------------------110Implicit Parameters and Views The implicit view, if it is found, can accept is argument e as a call-by-value or asa call-by-name parameter. However, call-by-value implicits take precedence overcall-by-name implicits.As for implicit parameters, overloading resolution is applied if there are several pos- sible candidates (of either the call-by-value or the call-by-name category) .Example 7.3.1 Class scala.Ordered[A] contains a methoddef <= [B >: A](that: B) (implicit b2ordered: B => Ordered[B]) : Boolean . Assume two lists xs and ys of type List[Int] and assume that the list2orderedand int2ordered methods defined in §7.2are in scope. Then the operationxs <= ysis legal, and is expanded to: list2ordered(xs) (int2ordered) .<=(ys)(xs => list2ordered(xs) (int2ordered) )The first application of list2ordered converts the list xs to an instance of classOrdered, whereas the second occurrence is part of an implicit parameter passed to the <= method.7.4Context Bounds and View BoundsSyntax:TypeParam ::= (id | `') [TypeParamClause] [`>:' Type] [`<:'Type]{`<%' Type} {`:' Type} A type parameter A of a method or non-trait class may have one or more viewbounds A <% T . In this case the type parameter may be instantiated to any typeS which is convertible by application of a view to the bound T . A type parameter A of a method or non-trait class may also have one or more con-text bounds A : T . In this case the type parameter may be instantiated to any typeS for which evidence exists at the instantiation point that S satisfies the bound T . Such evidence consists of an implicit value with type T [S].A method or class containing type parameters with view or context bounds istreated as being equivalent to a method with implicit parameters. Consider first the case of a single parameter with view and/or context bounds such as:def f [A <% T1 ... <% Tm : U1 : Un](ps) : R = ...------------------------------------------------------------------------------- 7.5 Manifests111Then the method definition above is expanded todef f [A](ps) (implicit v1: A => T1, ..., vm: A => Tm,w1: U1[A], ..., wn: Un[A]) : R = ...where the vi and w j are fresh names for the newly introduced implicit parameters. These parameters are called evidence parameters.If a class or method has several view- or context-bounded type parameters, eachsuch type parameter is expanded into evidence parameters in the order they appear and all the resulting evidence parameters are concatenated in one implicit param-eter section. Since traits do not take constructor parameters, this translation doesnot work for them. Consequently, type-parameters in traits may not be view- or context-bounded.Example 7.4.1 The <= method mentioned in Example 7.3.1can be declared moreconcisely as follows:def <= [B >: A <% Ordered[B]](that: B) : Boolean A method or class may define implicit parameters in addition to view- or contextbounds. In this case the implicit parameters are appended to the implicit parametersection of the evidence parameters. Example 7.4.2 Consider the following method definition:def f[A: Manifest](x: A) (implicit y: B) : RThen the method definition above is expanded to:def f[A](x: A) (implicit z: Manifest[A], y: B) : R 7.5ManifestsManifests are type descriptors that can be automatically generated by the Scalacompiler as arguments to implicit parameters. The Scala standard library contains a hierarchy of four manifest classes, with OptManifest at the top. Their signaturesfollow the outline below.trait OptManifest[+T]object NoManifest extends OptManifest[Nothing]trait ClassManifest[T] extends OptManifest[T] trait Manifest[T] extends ClassManifest[T]If an implicit parameter of a method or constructor is of a subtype M [T ] of classOptManifest[T], a manifest is determined for M [S], according to the following rules. -------------------------------------------------------------------------------112Implicit Parameters and ViewsFirst if there is already an implicit argument that matches M [T ], this argument is selected.Otherwise, let Mobj be the companion object scala.reflect.Manifest if M is traitManifest, or be the companion object scala.reflect.ClassManifest otherwise.Let M be the trait Manifest if M is trait Manifest, or be the trait OptManifest oth- erwise. Then the following rules apply.1. If T is a value class or one of the classes Any, AnyVal, Object, Null, or Nothing,a manifest for it is generated by selecting the corresponding manifest value Manifest.T , which exists in the Manifest module.2. If T is an instance of Array[S], a manifest is generated with the invocationMobj.arrayType[S](m) , where m is the manifest determined for M [S]. 3. If T is some other class type S#C [U1, ..., Un] where the prefix type S can-not be statically determined from the class C , a manifest is generated withthe invocation Mobj.classType[T](m0, classOf[T], ms) where m0 is the manifest determined for M [S] and ms are the manifests determined forM [U1], ..., M [Un].4. If T is some other class type with type arguments U1, ..., Un, a manifest isgenerated with the invocation Mobj.classType[T](classOf[T], ms) where ms are the manifests determined for M [U1], ..., M [Un].5. If T is a singleton type p.type, a manifest is generated with the invocationMobj.singleType[T](p)6. If T is a refined type T {R}, a manifest is generated for T . (That is, refinements are never reflected in manifests) .7. If T is an intersection type T1 with , ..., with Tn where n > 1, the re-sult depends on whether a full manifest is to be determined or not.If M is trait Manifest, then a manifest is generated with the invocationManifest.intersectionType[T](ms) where ms are the manifests deter-mined for M [T1], ..., M[Tn]. Otherwise, if M is trait ClassManifest, then a manifest is generated for the intersection dominator (§3.7) of the typesT1, ..., Tn.8. If T is some other type, then if M is trait OptManifest, a manifest is generatedfrom the designator scala.reflect.NoManifest. If M is a type different from OptManifest, a static error results.-------------------------------------------------------------------------------Chapter 8Pattern Matching8.1Patterns Syntax:Pattern::=Pattern1 { `|' Pattern1 }Pattern1::=varid `:' TypePat|`' `:' TypePat|Pattern2 Pattern2::=varid [`@' Pattern3]|Pattern3Pattern3::=SimplePattern|SimplePattern {id [nl] SimplePattern} SimplePattern::=`'|varid|Literal|StableId|StableId `(' [Patterns] `) '|StableId `(' [Patterns `,'] [varid `@'] `' `*' `) ' |`(' [Patterns] `) '|XmlPatternPatterns::=Pattern {`,' Patterns}A pattern is built from constants, constructors, variables and type tests. Pattern matching tests whether a given value (or sequence of values) has the shape definedby a pattern, and, if it does, binds the variables in the pattern to the correspondingcomponents of the value (or sequence of values) . The same variable name may not be bound more than once in a pattern.Example 8.1.1 Some examples of patterns are:1. The pattern ex: IOException matches all instances of class IOException,------------------------------------------------------------------------------- 114Pattern Matchingbinding variable ex to the instance.2. The pattern Some(x) matches values of the form Some(v) , binding x to theargument value v of the Some constructor. 3. The pattern (x, ) matches pairs of values, binding x to the first componentof the pair. The second component is matched with a wildcard pattern.4. The pattern x :: y :: xs matches lists of length 2, binding x to the list's first element, y to the list's second element, and xs to the remainder.5. The pattern 1 | 2 | 3 matches the integers between 1 and 3.Pattern matching is always done in a context which supplies an expected type of the pattern. We distinguish the following kinds of patterns.8.1.1 Variable PatternsSyntax:SimplePattern::=`'|varidA variable pattern x is a simple identifier which starts with a lower case letter. It matches any value, and binds the variable name to that value. The type of x is theexpected type of the pattern as given from outside. A special case is the wild-cardpattern _ which is treated as if it was a fresh variable on each occurrence. 8.1.2 Typed PatternsSyntax:Pattern1::=varid `:' TypePat|`' `:' TypePatA typed pattern x : T consists of a pattern variable x and a type pattern T . The type of x is the type pattern T , where each type variable and wildcard is replaced by afresh, unknown type. This pattern matches any value matched by the type patternT (§8.2) ;it binds the variable name to that value. 8.1.3 Pattern BindersSyntax:Pattern2::=varid `@' Pattern3A pattern binder x@p consists of a pattern variable x and a pattern p. The type ofthe variable x is the static type T of the pattern p. This pattern matches any value v matched by the pattern p, provided the run-time type of v is also an instance of T ,and it binds the variable name to that value.------------------------------------------------------------------------------- 8.1 Patterns1158.1.4 Literal PatternsSyntax:SimplePattern::=LiteralA literal pattern L matches any value that is equal (in terms of ==) to the literal L. The type of L must conform to the expected type of the pattern.8.1.5 Stable Identifier PatternsSyntax:SimplePattern::=StableIdA stable identifier pattern is a stable identifier r (§3.1) .The type of r must conform to the expected type of the pattern. The pattern matches any value v such thatr == v (§12.1) .To resolve the syntactic overlap with a variable pattern, a stable identifier patternmay not be a simple name starting with a lower-case letter. However, it is possible to enclose a such a variable name in backquotes; then it is treated as a stable identifierpattern.Example 8.1.2 Consider the following function definition:def f(x: Int, y: Int) = x match { case y => ...}Here, y is a variable pattern, which matches any value. If we wanted to turn thepattern into a stable identifier pattern, this can be achieved as follows: def f(x: Int, y: Int) = x match { case `y` => ...}Now, the pattern matches the y parameter of the enclosing function f. That is, thematch succeeds only if the x argument and the y argument of f are equal. 8.1.6 Constructor PatternsSyntax:SimplePattern::=StableId `(' [Patterns] `)A constructor pattern is of the form c(p1, ..., pn) where n 0. It consists of a stable identifier c, followed by element patterns p1, ..., pn. The constructor c is a simple-------------------------------------------------------------------------------116Pattern Matching or qualified name which denotes a case class (§5.3.2) .If the case class is monomor-phic, then it must conform to the expected type of the pattern, and the formal pa-rameter types of x's primary constructor (§5.3) are taken as the expected types of the element patterns p1, ..., pn. If the case class is polymorphic, then its type parame-ters are instantiated so that the instantiation of c conforms to the expected type ofthe pattern. The instantiated formal parameter types of c's primary constructor are then taken as the expected types of the component patterns p1, ..., pn. The patternmatches all objects created from constructor invocations c(v1, ..., vn) where eachelement pattern pi matches the corresponding value vi . A special case arises when c's formal parameter types end in a repeated parameter.This is further discussed in (§8.1.9) .8.1.7 Tuple PatternsSyntax:SimplePattern ::=`(' [Patterns] `) 'Atuplepattern(p1, . . . , pn)isanaliasfortheconstructorpattern scala.Tuplen(p1, . . . , pn) , where n 2.The empty tuple () is the uniquevalue of type scala.Unit.8.1.8 Extractor PatternsSyntax:SimplePattern::= StableId `(' [Patterns] `) 'An extractor pattern x(p1, ..., pn) where n 0 is of the same syntactic form as aconstructor pattern. However, instead of a case class, the stable identifier x denotes an object which has a member method named unapply or unapplySeq that matchesthe pattern.An unapply method in an object x matches the pattern x(p1, ..., pn) if it takes exactlyone argument and one of the following applies: n = 0 and unapply's result type is Boolean. In this case the extractor patternmatches all values v for which x.unapply(v) yields true.n = 1 and unapply's result type is Option[T ], for some type T . In this case, the (only) argument pattern p1 is typed in turn with expected type T . Theextractor pattern matches then all values v for which x.unapply(v) yields avalue of form Some(v1) , and p1 matches v1. n > 1 and unapply's result type is Option[(T1, ..., Tn) ], for some typesT1, ..., Tn. In this case, the argument patterns p1, ..., pn are typed in turnwith expected types T1, ..., Tn. The extractor pattern matches then all values -------------------------------------------------------------------------------8.1 Patterns117v for which x.unapply(v) yields a value of form Some((v1, ..., vn) ), and each pattern pi matches the corresponding value vi .An unapplySeq method in an object x matches the pattern x(p1, ..., pn) if it takesexactly one argument and its result type is of the form Option[S], where S is a sub- type of Seq[T ] for some element type T . This case is further discussed in (§8.1.9) .Example 8.1.3 The Predef object contains a definition of an extractor object Pair:object Pair {def apply[A, B](x: A, y: B) = Tuple2(x, y) def unapply[A, B](x: Tuple2[A, B]) : Option[Tuple2[A, B]] = Some(x)}This means that the name Pair can be used in place of Tuple2 for tuple formationas well as for deconstruction of tuples in patterns. Hence, the following is possible: val x = (1, 2)val y = x match {case Pair(i, s) => Pair(s + i, i * i)}8.1.9 Pattern SequencesSyntax:SimplePattern ::= StableId `(' [Patterns `,'] [varid `@'] `' `*' `) ' A pattern sequence p1, ..., pn appears in two contexts. First, in a constructor pat-tern c(q1, ..., qm, p1, ..., pn) , where c is a case class which has m + 1 primary con-structor parameters, ending in a repeated parameter (§4.6.2) of type S. Second, in an extractor pattern x(p1, ..., pn) if the extractor object x has an unapplySeqmethod with a result type conforming to Seq[S], but does not have an unapplymethod that matches p1, ..., pn. The expected type for the pattern sequence is in each case the type S.The last pattern in a pattern sequence may be a sequence wildcard *. Each ele-ment pattern pi is type-checked with S as expected type, unless it is a sequencewildcard. If a final sequence wildcard is present, the pattern matches all values v that are sequences which start with elements matching patterns p1, ..., pn-1. If nofinal sequence wildcard is given, the pattern matches all values v that are sequencesof length n which consist of elements matching patterns p1, ..., pn. 8.1.10 Infix Operation PatternsSyntax:-------------------------------------------------------------------------------118Pattern MatchingPattern3::= SimplePattern {id [nl] SimplePattern}An infix operation pattern p op q is a shorthand for the constructor or extractorpattern op(p, q) . The precedence and associativity of operators in patterns is the same as in expressions (§6.12) .An infix operation pattern p op (q1, ..., qn) is a shorthand for the constructor orextractor pattern op(p, q1, ..., qn) .8.1.11 Pattern Alternatives Syntax:Pattern::=Pattern1 { `|' Pattern1 }A pattern alternative p1 | ... | pn consists of a number of alternative patternspi . All alternative patterns are type checked with the expected type of the pattern. They may no bind variables other than wildcards. The alternative pattern matchesa value v if at least one its alternatives matches v.8.1.12 XML PatternsXML patterns are treated in §10.2. 8.1.13 Regular Expression PatternsRegular expression patterns have been discontinued in Scala from version 2.0.Later version of Scala provide a much simplified version of regular expression pat- terns that cover most scenarios of non-text sequence processing. A sequence patternis a pattern that stands in a position where either (1) a pattern of a type T which isconforming to Seq[A] for some A is expected, or (2) a case class constructor that has an iterated formal parameter A*. A wildcard star pattern * in the rightmost positionstands for arbitrary long sequences. It can be bound to variables using @, as usual,in which case the variable will have the type Seq[A]. 8.1.14 Irrefutable PatternsA pattern p is irrefutable for a type T , if one of the following applies:1. p is a variable pattern,2. p is a typed pattern x : T , and T <: T , 3. p is a constructor pattern c(p1, ..., pn) , the type T is an instance of class c, theprimary constructor (§5.3) of type T has argument types T1, ..., Tn, and eachpi is irrefutable for Ti . -------------------------------------------------------------------------------8.2 Type Patterns1198.2Type PatternsSyntax:TypePat::= Type Type patterns consist of types, type variables, and wildcards. A type pattern T is ofone of the following forms:· A reference to a class C , p.C , or T #C . This type pattern matches any non-null instance of the given class. Note that the prefix of the class, if it is given, is rel-evant for determining class instances. For instance, the pattern p.C matchesonly instances of classes C which were created with the path p as prefix. The bottom types scala.Nothing and scala.Null cannot be used as type pat-terns, because they would match nothing in any case.· A singleton type p.type. This type pattern matches only the value denoted by the path p (that is, a pattern match involved a comparison of the matchedvalue with p using method eq in class AnyRef) .· A compound type pattern T1 with ... with Tn where each Ti is a type pat- tern. This type pattern matches all values that are matched by each of the typepatterns Ti .· A parameterized type pattern T [a1, ..., an], where the ai are type variable pat-terns or wildcards . This type pattern matches all values which match T for some arbitrary instantiation of the type variables and wildcards. The boundsor alias type of these type variable are determined as described in (§8.3) .· A parameterized type pattern scala.Array[T1], where T1 is a type pattern. This type pattern matches any non-null instance of type scala.Array[U1],where U1 is a type matched by T1.Types which are not of one of the forms described above are also accepted as type patterns. However, such type patterns will be translated to their erasure (§3.7) .TheScala compiler will issue an "unchecked" warning for these patterns to flag the pos-sible loss of type-safety. A type variable pattern is a simple identifier which starts with a lower case letter.However, the predefined primitive type aliases unit, boolean, byte, short, char,int, long, float, and double are not classified as type variable patterns. 8.3Type Parameter Inference in PatternsType parameter inference is the process of finding bounds for the bound type vari-ables in a typed pattern or constructor pattern. Inference takes into account the expected type of the pattern.-------------------------------------------------------------------------------120Pattern MatchingType parameter inference for typed patterns.. Assume a typed pattern p : T . LetT result from T where all wildcards in T are renamed to fresh variable names. Leta1, ..., an be the type variables in T . These type variables are considered bound in the pattern. Let the expected type of the pattern be pt.Type parameter inference constructs first a set of subtype constraints over the typevariables ai . The initial constraints set C0 reflects just the bounds of these type vari- ables. That is, assuming T has bound type variables a1, ..., an which correspondto class type parameters a , . . . , a1n with lower bounds L1, . . . , Ln and upper boundsU1, ..., Un, C0 contains the constraints ai <: Ui(i = 1, ..., n)Li <: ai(i = 1, ..., n)where is the substitution [a :1 = a1, . . . , an := an ].The set C0 is then augmented by further subtype constraints. There are two cases. Case 1:.If there exists a substitution over the type variables ai , ..., an such thatT conforms to pt, one determines the weakest subtype constraints C1 over thetype variables a1, ..., an such that C0  C1 implies that T conforms to pt. Case 2:.Otherwise, if T can not be made to conform to pt by instantiating its typevariables, one determines all type variables in pt which are defined as type param-eters of a method enclosing the pattern. Let the set of such type parameters be b1, ..., bm. Let C be the subtype constraints reflecting the bounds of the type vari-0ables bi . If T denotes an instance type of a final class, let C2 be the weakest setof subtype constraints over the type variables a1, ..., an and b1, ..., bm such that C0  C0  C2 implies that T conforms to pt. If T does not denote an instance typeof a final class, let C2 be the weakest set of subtype constraints over the type vari-ables a1, ..., an and b1, ..., bm such that C0  C0  C2 implies that it is possible to construct a type T which conforms to both T and pt. It is a static error if there is nosatisfiable set of constraints C2 with this property.The final step consists in choosing type bounds for the type variables which imply the established constraint system. The process is different for the two cases above.Case 1:.We take ai >: Li <: Ui where each Li is minimal and each Ui is maximalwrt <: such that ai >: Li <: Ui for i = 1, ..., n implies C0  C1. Case 2:.We take ai >: Li <: Ui and bi >: Lwhere each Lis minimali <: Uii and L jand each Ui and U is maximal such that aj i >: Li <: Ui for i = 1, . . . , n and b j >:Lfor jj <: U j= 1, . . . , m implies C0  C0  C2.------------------------------------------------------------------------------- 8.3 Type Parameter Inference in Patterns121In both cases, local type inference is permitted to limit the complexity of inferredbounds. Minimality and maximality of types have to be understood relative to the set of types of acceptable complexity.Type parameter inference for constructor patterns..Assume a constructor pat-tern C (p1, ..., pn) where class C has type type parameters a1, ..., an. These type pa- rameters are inferred in the same way as for the typed pattern (: C [a1, ..., an]) .Example 8.3.1 Consider the program fragment:val x: Anyx match {case y: List[a] => ... }Here, the type pattern List[a] is matched against the expected type Any. The pat-tern binds the type variable a. Since List[a] conforms to Any for every type argu-ment, there are no constraints on a. Hence, a is introduced as an abstract type with no bounds. The scope of a is right-hand side of its case clause.On the other hand, if x is declared asval x: List[List[String]],this generates the constraint List[a] <: List[List[String]], which simplifies to a <: List[String], because List is covariant. Hence, a is introduced with upperbound List[String].Example 8.3.2 Consider the program fragment:val x: Anyx match { case y: List[String] => ...}Scala does not maintain information about type arguments at run-time, so there isno way to check that x is a list of strings. Instead, the Scala compiler will erase (§3.7) the pattern to List[]; that is, it will only test whether the top-level runtime-classof the value x conforms to List, and the pattern match will succeed if it does. Thismight lead to a class cast exception later on, in the case where the list x contains elements other than strings. The Scala compiler will flag this potential loss of type-safety with an "unchecked" warning message.Example 8.3.3 Consider the program fragment class Term[A] -------------------------------------------------------------------------------122Pattern Matchingclass Number(val n: Int) extends Term[Int]def f[B](t: Term[B]) : B = t match { case y: Number => y.n}The expected type of the pattern y: Number is Term[B]. The type Number does notconform to Term[B]; hence Case 2 of the rules above applies. This means that b is treated as another type variable for which subtype constraints are inferred. Inour case the applicable constraint is Number <: Term[B], which entails B = Int.Hence, B is treated in the case clause as an abstract type with lower and upper bound Int. Therefore, the right hand side of the case clause, y.n, of type Int, is found toconform to the function's declared result type, Number.8.4Pattern Matching Expressions Syntax:Expr::=PostfixExpr `match' `{' CaseClauses `}'CaseClauses::=CaseClause {CaseClause}CaseClause::=`case' Pattern [Guard] `=>' Block A pattern matching expressione match { case p1 => b1 . . . case pn => bn }consists of a selector expression e and a number n > 0 of cases. Each case consistsof a (possibly guarded) pattern pi and a block bi . Each pi might be complemented by a guard if e where e is a boolean expression. The scope of the pattern variablesin pi comprises the pattern's guard and the corresponding block bi .Let T be the type of the selector expression e and let a1, ..., am be the type param- eters of all methods enclosing the pattern matching expression. For every ai , let Libe its lower bound and Ui be its higher bound. Every pattern p {p1,, ..., pn} canbe typed in two ways. First, it is attempted to type p with T as its expected type. If this fails, p is instead typed with a modified expected type T which results from Tby replacing every occurrence of a type parameter ai by undefined. If this secondstep fails also, a compile-time error results. If the second step succeeds, let Tp be the type of pattern p seen as an expression. One then determines minimal boundsL , . . . , L, . . . , Uand U1m and maximal bounds U1m such that for all i , Li <: Li i <: Uiand the following constraint system is satisfied:L1 <: a1 <: U1  ... Lm <: am <: Um  Tp <: TIf no such bounds can be found, a compile time error results. If such bounds are found, the pattern matching clause starting with p is then typed under the assump--------------------------------------------------------------------------------8.4 Pattern Matching Expressions 123tion that each ai has lower bound L instead of Linsteadii and has upper bound Uiof Ui .The expected type of every block bi is the expected type of the whole pattern match- ing expression. The type of the pattern matching expression is then the weak leastupper bound (§3.5.3) of the types of all blocks bi .When applying a pattern matching expression to a selector value, patterns are tried in sequence until one is found which matches the selector value (§8.1) .Say this caseis case pi  bi . The result of the whole expression is then the result of evaluating bi ,where all pattern variables of pi are bound to the corresponding parts of the selector value. If no matching pattern is found, a scala.MatchError exception is thrown.The pattern in a case may also be followed by a guard suffix if e with a booleanexpression e. The guard expression is evaluated if the preceding pattern in the case matches. If the guard expression evaluates to true, the pattern match succeeds asnormal. If the guard expression evaluates to false, the pattern in the case is con-sidered not to match and the search for a matching pattern continues. In the interest of efficiency the evaluation of a pattern matching expression may trypatterns in some other order than textual sequence. This might affect evaluationthrough side effects in guards. However, it is guaranteed that a guard expression is evaluated only if the pattern it guards matches.If the selector of a pattern match is an instance of a sealed class (§5.2) ,the com-pilation of pattern matching can emit warnings which diagnose that a given set of patterns is not exhaustive, i.e. that there is a possibility of a MatchError being raisedat run-time.Example 8.4.1 Consider the following definitions of arithmetic terms:abstract class Term[T] case class Lit(x: Int) extends Term[Int]case class Succ(t: Term[Int]) extends Term[Int]case class IsZero(t: Term[Int]) extends Term[Boolean]case class If[T](c: Term[Boolean], t1: Term[T],t2: Term[T]) extends Term[T]There are terms to represent numeric literals, incrementation, a zero test, and aconditional. Every term carries as a type parameter the type of the expression it representes (either Int or Boolean) .A type-safe evaluator for such terms can be written as follows.def eval[T](t: Term[T]) : T = t match {case Lit(n)=> ncase Succ(u) => eval(u) + 1case IsZero(u)=> eval(u) == 0case If(c, u1, u2) => eval(if (eval(c) ) u1 else u2)------------------------------------------------------------------------------- 124Pattern Matching}Note that the evaluator makes crucial use of the fact that type parameters of enclos-ing methods can acquire new bounds through pattern matching. For instance, the type of the pattern in the second case, Succ(u) , is Int. It conformsto the selector type T only if we assume an upper and lower bound of Int for T.Under the assumption Int <: T <: Int we can also verify that the type right hand side of the second case, Int conforms to its expected type, T.8.5Pattern Matching Anonymous FunctionsSyntax:BlockExpr ::= `{' CaseClauses `}'An anonymous function can be defined by a sequence of cases { case p1 => b1 . . . case pn => bn }whichappearasanexpressionwithoutapriormatch.Theex- pectedtypeofsuchanexpressionmustinpartbedefined.Itmust be eitherscala.Functionk[S1, . . . , Sk, R] for some k > 0, orscala.PartialFunction[S1, R], where the argument type(s) S1, . . . , Sk mustbe fully determined, but the result type R may be undetermined.If the expected type is scala.Functionk[S1, ..., Sk, R] , the expression is taken to be equivalent to the anonymous function:(x1 : S1, . . . , xk : Sk) => (x1, . . . , xk) match {case p1 => b1 . . . case pn => bn}Here, each xi is a fresh name. As was shown in (§6.23) ,this anonymous function is in turn equivalent to the following instance creation expression, where T is theweak least upper bound of the types of all bi .new scala.Functionk[S1, . . . , Sk, T ] {def apply(x1 : S1, . . . , xk : Sk) : T = (x1, . . . , xk) match { case p1 => b1 . . . case pn => bn}}If the expected type is scala.PartialFunction[S, R], the expression is taken tobe equivalent to the following instance creation expression: new scala.PartialFunction[S, T ] {-------------------------------------------------------------------------------8.5 Pattern Matching Anonymous Functions125def apply(x: S) : T = x match { case p1 => b1 . . . case pn => bn}def isDefinedAt(x: S) : Boolean = {case p1 => true . . . case pn => truecase _ => false}} Here, x is a fresh name and T is the weak least upper bound of the types of all bi . The final default case in the isDefinedAt method is omitted if one of the patternsp1, ..., pn is already a variable or wildcard pattern.Example 8.5.1 Here is a method which uses a fold-left operation /: to compute the scalar product of two vectors:def scalarProduct(xs: Array[Double], ys: Array[Double]) =(0.0 /: (xs zip ys) ) {case (a, (b, c) ) => a + b * c}The case clauses in this code are equivalent to the following anonymous funciton: (x, y) => (x, y) match {case (a, (b, c) ) => a + b * c}-------------------------------------------------------------------------------------------------------------------------------------------------------------- Chapter 9Top-Level Definitions9.1Compilation UnitsSyntax:CompilationUnit::={`package' QualId semi} TopStatSeqTopStatSeq ::=TopStat {semi TopStat}TopStat::={Annotation} {Modifier} TmplDef|Import|Packaging|PackageObject |QualId::=id {`.' id}A compilation unit consists of a sequence of packagings, import clauses, and classand object definitions, which may be preceded by a package clause. A compilation unitpackage p1;. . .package pn;statsstarting with one or more package clauses is equivalent to a compilation unit con-sisting of the packaging package p1 { . . .package pn {stats} . . .}-------------------------------------------------------------------------------128Top-Level Definitions Implicitly imported into every compilation unit are, in that order : the packagejava.lang, the package scala, and the object scala.Predef (§12.5) .Members ofa later import in that order hide members of an earlier import. 9.2PackagingsSyntax:Packaging::=`package' QualId [nl] `{' TopStatSeq `}'A package is a special object which defines a set of member classes, objects and packages. Unlike other objects, packages are not introduced by a definition. In-stead, the set of members of a package is determined by packagings.A packaging package p { ds } injects all definitions in ds as members into the package whose qualified name is p. Members of a package are called top-level def-initions. If a definition in ds is labeled private, it is visible only for other membersin the package. Inside the packaging, all members of package p are visible under their simplenames. However this rule does not extend to members of enclosing packages ofp that are designated by a prefix of the path p. Example 9.2.1 Given the packagingpackage org.net.prj {...}all members of package org.net.prj are visible under their simple names, butmembers of packages org or org.net require explicit qualification or imports. Selections p.m from p as well as imports from p work as for objects. However, unlikeother objects, packages may not be used as values. It is illegal to have a package withthe same fully qualified name as a module or a class. Top-level definitions outside a packaging are assumed to be injected into a specialempty package. That package cannot be named and therefore cannot be imported.However, members of the empty package are visible to each other without qualifi- cation.9.3Package ObjectsSyntax:PackageObject::=`package' `object' ObjectDef------------------------------------------------------------------------------- 9.4 Package References129A package object package object p extends t adds the members of template tto the package p. There can be only one package object per package. The standard naming convention is to place the definition above in a file named package.scalathat's located in the directory corresponding to package p.The package object should not define a member with the same name as one of the top-level objects or classes defined in package p. If there is a name conflict, thebehavior of the program is currently undefined. It is expected that this restrictionwill be lifted in a future version of Scala. 9.4Package ReferencesSyntax:QualId::=id {`.' id}A reference to a package takes the form of a qualified identifier. Like all other ref- erences, package references are relative. That is, a package reference starting in a name p will be looked up in the closest enclosing scope that defines a membernamed p.The special predefined name root_ refers to the outermost root package whichcontains all top-level packages. Example 9.4.1 Consider the following program:package b {class B}package a.b {class A {val x = new root.b.B}}Here, the reference root.b.B refers to class B in the toplevel package b. If the root_ prefix had been omitted, the name b would instead resolve to the packagea.b, and, provided that package does not also contain a class B, a compiler-timeerror would result.9.5 ProgramsA program is a top-level object that has a member method main of type(Array[String]) Unit. Programs can be executed from a command shell. The pro-------------------------------------------------------------------------------- 130Top-Level Definitionsgram's command arguments are are passed to the main method as a parameter oftype Array[String].The main method of a program can be directly defined in the object, or it can be inherited. The scala library defines a class scala.App that defines an empty inher-ited main method. An objects m inheriting from this class is thus a program, whichexecutes the initializaton code of the object m. Example 9.5.1 The following example will create a hello world program by defininga method main in module test.HelloWorld.package testobject HelloWord {def main(args: Array[String]) { println("hello world") } }This program can be started by the commandscala test.HelloWorldIn a Java environment, the commandjava test.HelloWorldwould work as well.HelloWorld can also be defined without a main method by inheriting from App in- stead:package testobject HelloWord extends App {println("hello world")}------------------------------------------------------------------------------- Chapter 10XML expressions and patternsBy Burak EmirThis chapter describes the syntactic structure of XML expressions and patterns. Itfollows as closely as possible the XML 1.0 specification [W3C],changes being man- dated by the possibility of embedding Scala code fragments.10.1XML expressionsXML expressions are expressions generated by the following production, where theopening bracket `<' of the first element must be in a position to start the lexical XML mode (§1.5) .Syntax:XmlExpr ::= XmlContent {Element}Well-formedness constraints of the XML specification apply, which means for in-stance that start tags and end tags must match, and attributes may only be defined once, with the exception of constraints related to entity resolution.The following productions describe Scala's extensible markup language, designedas close as possible to the W3C extensible markup language standard. Only the pro- ductions for attribute values and character data are changed. Scala does not sup-port declarations, CDATA sections or processing instructions. Entity references arenot resolved at runtime. Syntax:Element::=EmptyElemTag|STag Content ETag-------------------------------------------------------------------------------132 XML expressions and patternsEmptyElemTag::=`<' Name {S Attribute} [S] `/>'STag::=`<' Name {S Attribute} [S] `>'ETag ::=`</' Name [S] '>'Content::=[CharData] {Content1 [CharData]}Content1::=XmlContent|Reference |ScalaExprXmlContent::=Element|CDSect|PI|CommentIf an XML expression is a single element, its value is a runtime representation of an XML node (an instance of a subclass of scala.xml.Node) . If the XML expressionconsists of more than one element, then its value is a runtime representation of asequence of XML nodes (an instance of a subclass of scala.Seq[scala.xml.Node]) . If an XML expression is an entity reference, CDATA section, processing instructionsor a comments, it is represented by an instance of the corresponding Scala runtimeclass.By default, beginning and trailing whitespace in element content is removed, and consecutive occurrences of whitespace are replaced by a single space character\u0020. This behavior can be changed to preserve all whitespace with a compileroption.Syntax: Attribute ::=Name Eq AttValueAttValue::=`"' {CharQ | CharRef} `"'|`'' {CharA | CharRef} `''|ScalaExpr ScalaExpr::=BlockCharData::={ CharNoRef } without {CharNoRef}`{'CharB {CharNoRef}and without {CharNoRef}`]]>'{CharNoRef}XML expressions may contain Scala expressions as attribute values or within nodes. In the latter case, these are embedded using a single opening brace `{' and ended bya closing brace `}'. To express a single opening braces within XML text as generatedby CharData, it must be doubled. Thus, `{{' represents the XML text `{' and does not introduce an embedded Scala expression.Syntax:-------------------------------------------------------------------------------10.2 XML patterns133BaseChar, Char, Comment, CombiningChar, Ideographic, NameChar, S, Reference ::="as in W3C XML"Char1::=Char without `<' | `&'CharQ::=Char1 without `"'CharA::= Char1 without `''CharB::=Char1 without '{'Name::=XNameStart {NameChar}XNameStart::= `' | BaseChar | Ideographic (as in W3C XML, but without `:'10.2XML patternsXML patterns are patterns generated by the following production, where the open-ing bracket `<' of the element patterns must be in a position to start the lexical XML mode (§1.5) .Syntax:XmlPattern::= ElementPatternWell-formedness constraints of the XML specification apply.An XML pattern has to be a single element pattern. It matches exactly those runtime representations of an XML tree that have the same structure as described by thepattern. XML patterns may contain Scala patterns(§8.4) .Whitespace is treated the same way as in XML expressions. Patterns that are entity references, CDATA sections, processing instructions and comments match runtimerepresentations which are the the same.By default, beginning and trailing whitespace in element content is removed, and consecutive occurrences of whitespace are replaced by a single space character\u0020. This behavior can be changed to preserve all whitespace with a compileroption.Syntax: ElemPattern ::=EmptyElemTagP|STagP ContentP ETagPEmptyElemTagP ::=`<' Name [S] `/>'STagP::=`<' Name [S] `>' ETagP::=`</' Name [S]`>'ContentP::=[CharData] {(ElemPattern|ScalaPatterns) [CharData]}------------------------------------------------------------------------------- 134XML expressions and patternsContentP1::=ElemPattern|Reference|CDSect|PI|Comment |ScalaPatternsScalaPatterns ::=`{' Patterns `}'-------------------------------------------------------------------------------Chapter 11User-Defined Annotations Syntax:Annotation::=`@' SimpleType {ArgumentExprs}ConstrAnnotation ::=`@' SimpleType ArgumentExprsUser-defined annotations associate meta-information with definitions. A simple annotation has the form @c or @c(a1, ..., an) . Here, c is a constructor of a class C ,which must conform to the class scala.Annotation.Annotations may apply to definitions or declarations, types, or expressions. An an- notation of a definition or declaration appears in front of that definition. An anno-tation of a type appears after that type. An annotation of an expression e appearsafter the expression e, separated by a colon. More than one annotation clause may apply to an entity. The order in which these annotations are given does not matter.Examples:@serializable class C { ... }// A class annotation.@transient @volatile var m: Int // A variable annotationString @local// A type annotation(e: @unchecked) match { ... }// An expression annotationThe meaning of annotation clauses is implementation-dependent. On the Java plat- form, the following annotations have a standard meaning.@transientMarks a field to be non-persistent; this is equivalent to the transientmodifier in Java.@volatile -------------------------------------------------------------------------------136User-Defined AnnotationsMarks a field which can change its value outside the control of the pro- gram; this is equivalent to the volatile modifier in Java.@serializableMarks a class to be serializable; this is equivalent to inheriting from thejava.io.Serializable interface in Java. @SerialVersionUID(<longlit>)Attaches a serial version identifier (a long constant) to a class. This isequivalent to a the following field definition in Java:private final static SerialVersionUID = <longlit> @throws(<classlit>)A Java compiler checks that a program contains handlers for checkedexceptions by analyzing which checked exceptions can result from exe-cution of a method or constructor. For each checked exception which is a possible result, the throws clause for the method or constructor mustmention the class of that exception or one of the superclasses of theclass of that exception.@deprecated(<stringlit>) Marks a definition as deprecated. Accesses to the defined entity willthen cause a deprecated warning mentioning the message <stringlit>to be issued from the compiler. Deprecated warnings are suppressed in code that belongs itself to a definition that is labeled deprecated [dot] [at] scala [dot] reflect [dot] BeanPropertyWhen prefixed to a definition of some variable X, this annotation causesgetter and setter methods getX, setX in the Java bean style to be added in the class containing the variable. The first letter of the variable ap-pears capitalized after the get or set. When the annotation is added tothe definition of an immutable value definition X, only a getter is gen- erated. The construction of these methods is part of code-generation;therefore, these methods become visible only once a classfile for thecontaining class is generated [dot] [at] scala [dot] reflect [dot] BooleanBeanProperty -------------------------------------------------------------------------------137This annotation is equivalent to scala.reflect.BeanProperty, but thegenerated getter method is named isX instead of getX. @uncheckedWhen applied to the selector of a match expression, this attribute sup-presses any warnings about non-exhaustive pattern matches whichwould otherwise be emitted. For instance, no warnings would be pro- duced for the method definition below.def f(x: Option[Int]) = (x: @unchecked) match {case Some(y) => y}Without the @unchecked annotation, a Scala compiler could infer that the pattern match is non-exhaustive, and could produce a warning be-cause Option is a sealed class.@uncheckedStableWhen applied a value declaration or definition, it allows the defined value to appear in a path, even if its type is volatile (§??) . For instance,the following member definitions are legal:type A { type T }type B@uncheckedStable val x: A with B // volatile type val y: x.T// OK since `x' is still a pathWithout the @uncheckedStable annotation, the designator x would notbe a path since its type A with B is volatile. Hence, the reference x.T would be malformed.When applied to value declarations or definitions that have non-volatiletypes, the annotation has no effect.@specializedWhen applied to the definition of a type parameter, this annotation causes the compiler to generate specialized definitions for primitivetypes. An optional list of primitive types may be given, in which casespecialization takes into account only those types. For instance, the fol- lowing code would generate specialized traits for Unit, Int and Doubletrait Function0[@specialized(Unit, Int, Double) T] {def apply: T}------------------------------------------------------------------------------- 138User-Defined AnnotationsWhenever the static type of an expression matches a specialized variantof a definition, the compiler will instead use the specialized version. See [Dra10]for more details of the implementation.Other annotations may be interpreted by platform- or application-dependent tools.Class scala.Annotation has two sub-traits which are used to indicate how these annotations are retained. Instances of an annotation class inheriting from traitscala.ClassfileAnnotation will be stored in the generated class files. Instancesof an annotation class inheriting from trait scala.StaticAnnotation will be visible to the Scala type-checker in every compilation unit where the annotated symbol isaccessed. An annotation class can inherit from both scala.ClassfileAnnotationand scala.StaticAnnotation. If an annotation class inherits from neitherscala.ClassfileAnnotation nor scala.StaticAnnotation, its instances are visibleonly locally during the compilation run that analyzes them.Classes inheriting from scala.ClassfileAnnotation may be subject to further re- strictions in order to assure that they can be mapped to the host environment. Inparticular, on both the Java and the .NET platforms, such classes must be toplevel;i.e. they may not be contained in another class or object. Additionally, on both Java and .NET, all constructor arguments must be constant expressions.-------------------------------------------------------------------------------Chapter 12The Scala Standard Library The Scala standard library consists of the package scala with a number of classesand modules. Some of these classes are described in the following.12.1Root ClassesFigure 12.1illustrates Scala's class hierarchy. The root of this hierarchy is formed by class Any. Every class in a Scala execution environment inherits directly or indirectlyfrom this class. Class Any has two direct subclasses: AnyRef and AnyVal.The subclass AnyRef represents all values which are represented as objects in the underlying host system. Every user-defined Scala class inherits directly or indi-rectly from this class. Furthermore, every user-defined Scala class also inheritsthe trait scala.ScalaObject. Classes written in other languages still inherit from scala.AnyRef, but not from scala.ScalaObject.The class AnyVal has a fixed number of subclasses, which describe values which arenot implemented as objects in the underlying host system. Classes AnyRef and AnyVal are required to provide only the members declared inclass Any, but implementations may add host-specific methods to these classes (forinstance, an implementation may identify class AnyRef with its own root class for objects) .The signatures of these root classes are described by the following definitions.package scala/** The universal root class */abstract class Any {/** Defined equality; abstract here */ def equals(that: Any) : Boolean-------------------------------------------------------------------------------140The Scala Standard LibraryO(j aa.l a.bjet)ngcvFigure 12.1: Class hierarchy of Scala./** Semantic equality between values */ final def == (that: Any) : Boolean=if (null eq this) null eq that else this equals that/** Semantic inequality between values */final def != (that: Any) : Boolean =!(this == that)/** Hash code; abstract here */def hashCode: Int = . . ./** Textual representation; abstract here */def toString: String = . . ./** Type test; needs to be inlined to work as given */ def isInstanceOf[a]: Boolean/** Type cast; needs to be inlined to work as given */ */def asInstanceOf[A]: A = this match {case x: A => xcase _ => if (this eq null) this else throw new ClassCastException()}}-------------------------------------------------------------------------------12.2 Value Classes141/** The root class of all value types */ final class AnyVal extends Any/** The root class of all reference types */class AnyRef extends Any {def equals(that: Any) : Boolean= this eq thatfinal def eq(that: AnyRef) : Boolean = . . . // reference equality final def ne(that: AnyRef) : Boolean = !(this eq that)def hashCode: Int = . . .// hashCode computed from allocation addressdef toString: String= . . . // toString computed from hashCode and class name def synchronized[T](body: => T) : T // execute `body` in while locking `this`.}/** A mixin class for every user-defined Scala class */trait ScalaObject extends AnyRefThe type test x.isInstanceOf[T ] is equivalent to a typed pattern match x match {case : T=> truecase _ => false}where the type T is the same as T except if T is of the form D or D[tps] whereD is a type member of some outer class C . In this case T is C #D (or C #D[t ps], respectively) , whereas T itself would expand to C .this.D[t p s]. In other words, anisInstanceOf test does not check for theThe test x.asInstanceOf[T ] is treated specially if T is a numeric value type (§12.2) .In this case the cast will be translated to an application of a conversionmethod x.toT (§12.2.1) .For non-numeric values x the operation will raise aClassCastException.12.2 Value ClassesValue classes are classes whose instances are not represented as objects by the un-derlying host system. All value classes inherit from class AnyVal. Scala implemen-tations need to provide the value classes Unit, Boolean, Double, Float, Long, Int, Char, Short, and Byte (but are free to provide others as well) . The signatures ofthese classes are defined in the following.------------------------------------------------------------------------------- 142The Scala Standard Library12.2.1 Numeric Value TypesClasses Double, Float, Long, Int, Char, Short, and Byte are together called numericvalue types. Classes Byte, Short, or Char are called subrange types. Subrange types, as well as Int and Long are called integer types, whereas Float and Double are calledfloating point types.Numeric value types are ranked in the following partial order:Byte - Short \Int - Long - Float - Double/CharByte and Short are the lowest-ranked types in this order, whereas Double is thehighest-ranked. Ranking does not imply a conformance (§3.5.2) relationship; for instance Int is not a subtype of Long. However, object Predef (§12.5) defines views(§7.3) from every numeric value type to all higher-ranked numeric value types.Therefore, lower-ranked types are implicitly converted to higher-ranked types when required by the context (§6.26) .Given two numeric value types S and T , the operation type of S and T is defined asfollows: If both S and T are subrange types then the operation type of S and T is Int. Otherwise the operation type of S and T is the larger of the two types wrt ranking.Given two numeric values v and w the operation type of v and w is the operationtype of their run-time types. Any numeric value type T supports the following methods.· Comparison methods for equals (==) , not-equals (!=) , less-than (<) , greater-than (>) , less-than-or-equals (<=) , greater-than-or-equals (>=) , which each ex- ist in 7 overloaded alternatives. Each alternative takes a parameter of somenumeric value type. Its result type is type Boolean. The operation is evalu-ated by converting the receiver and its argument to their operation type and performing the given comparison operation of that type.· Arithmetic methods addition (+) , subtraction (-) , multiplication (*) , division(/) , and remainder (%) , which each exist in 7 overloaded alternatives. Each alternative takes a parameter of some numeric value type U . Its result type isthe operation type of T and U . The operation is evaluated by converting thereceiver and its argument to their operation type and performing the given arithmetic operation of that type.· Parameterless arithmethic methods identity (+) and negation (-) , with resulttype T . The first of these returns the receiver unchanged, whereas the second returns its negation.· Conversion methods toByte, toShort, toChar, toInt, toLong, toFloat,-------------------------------------------------------------------------------12.2 Value Classes 143toDouble which convert the receiver object to the target type, using the rulesof Java's numeric type cast operation. The conversion might truncate the nu-meric value (as when going from Long to Int or from Int to Byte) or it might lose precision (as when going from Double to Float or when converting be-tween Long and Float) .Integer numeric value types support in addition the following operations:· Bit manipulation methods bitwise-and (&) , bitwise-or |, and bitwise- exclusive-or (^) , which each exist in 5 overloaded alternatives. Each alterna-tive takes a parameter of some integer numeric value type. Its result type isthe operation type of T and U . The operation is evaluated by converting the receiver and its argument to their operation type and performing the givenbitwise operation of that type.· A parameterless bit-negation method (~) . Its result type is the reciver type T or Int, whichever is larger. The operation is evaluated by converting the receiverto the result type and negating every bit in its value.· Bit-shift methods left-shift (<<) , arithmetic right-shift (>>) , and unsigned right-shift (>>>) . Each of these methods has two overloaded alternatives,which take a parameter n of type Int, respectively Long. The result type ofthe operation is the receiver type T , or Int, whichever is larger. The operation is evaluated by converting the receiver to the result type and performing thespecified shift by n bits.Numeric value types also implement operations equals, hashCode, and toStringfrom class Any. The equals method tests whether the argument is a numeric value type. If this istrue, it will perform the == operation which is appropriate for that type. That is, theequals method of a numeric value type can be thought of being defined as follows: def equals(other: Any) : Boolean = other match {case that: Byte=> this == thatcase that: Short=> this == thatcase that: Char=> this == that case that: Int=> this == thatcase that: Long=> this == thatcase that: Float=> this == thatcase that: Double => this == thatcase _ => false }The hashCode method returns an integer hashcode that maps equal numeric val-ues to equal results. It is guaranteed to be the identity for for type Int and for allsubrange types. -------------------------------------------------------------------------------144The Scala Standard LibraryThe toString method displays its receiver as an integer or floating point number. Example 12.2.1 As an example, here is the signature of the numeric value type Int:package scalaabstract sealed class Int extends AnyVal {def == (that: Double) : Boolean// double equality def == (that: Float) : Boolean// float equalitydef == (that: Long) : Boolean// long equalitydef == (that: Int) : Boolean// int equalitydef == (that: Short) : Boolean // int equalitydef == (that: Byte) : Boolean// int equalitydef == (that: Char) : Boolean// int equality/* analogous for !=, <, >, <=, >= */ def + (that: Double) : Double// double additiondef + (that: Float) : Double// float additiondef + (that: Long) : Long// long additiondef + (that: Int) : Int // int additiondef + (that: Short) : Int// int additiondef + (that: Byte) : Int// int additiondef + (that: Char) : Int// int addition/* analogous for -, *, /, % */ def & (that: Long) : Long// long bitwise anddef & (that: Int) : Int// int bitwise anddef & (that: Short) : Int// int bitwise anddef & (that: Byte) : Int // int bitwise anddef & (that: Char) : Int// int bitwise and/* analogous for |, ^ */def << (cnt: Int) : Int// int left shiftdef << (cnt: Long) : Int // long left shift/* analogous for >>, >>> */def unary+ : Int// int identitydef unary- : Int// int negationdef unary~ : Int // int bitwise negation def toByte: Byte// convert to Bytedef toShort: Short// convert to Shortdef toChar: Char// convert to Chardef toInt: Int// convert to Int def toLong: Long// convert to Longdef toFloat: Float// convert to Floatdef toDouble: Double// convert to Double}------------------------------------------------------------------------------- 12.3 Standard Reference Classes14512.2.2 Class BooleanClass Boolean has only two values: true and false. It implements operations asgiven in the following class definition. package scalaabstract sealed class Boolean extends AnyVal {def && (p: => Boolean) : Boolean = // boolean andif (this) p else falsedef || (p: => Boolean) : Boolean = // boolean or if (this) true else pdef &(x: Boolean) : Boolean =// boolean strict andif (this) x else falsedef |(x: Boolean) : Boolean =// boolean strict or if (this) true else xdef == (x: Boolean) : Boolean =// boolean equalityif (this) x else x.unary!def != (x: Boolean) : Boolean// boolean inequalityif (this) x.unary! else x def unary!: Boolean// boolean negationif (this) false else true}The class also implements operations equals, hashCode, and toString from classAny.The equals method returns true if the argument is the same boolean value as the receiver, false otherwise. The hashCode method returns a fixed, implementation-specific hash-code when invoked on true, and a different, fixed, implementation-specific hash-code when invoked on false. The toString method returns the re- ceiver converted to a string, i.e. either "true" or "false".12.2.3 Class UnitClass Unit has only one value: () . It implements only the three methods equals,hashCode, and toString from class Any. The equals method returns true if the argument is the unit value () , false oth-erwise. The hashCode method returns a fixed, implementation-specific hash-code,The toString method returns "() ". 12.3Standard Reference ClassesThis section presents some standard Scala reference classes which are treated in aspecial way in Scala compiler ­ either Scala provides syntactic sugar for them, or the Scala compiler generates special code for their operations. Other classes in the-------------------------------------------------------------------------------146The Scala Standard Library standard Scala library are documented in the Scala library documentation by HTMLpages.12.3.1 Class StringScala's String class is usually derived from the standard String class of the underly- ing host system (and may be identified with it) . For Scala clients the class is takento support in each case a methoddef + (that: Any) : Stringwhich concatenates its left operand with the textual representation of its right operand.12.3.2 The Tuple classesScala defines tuple classes Tuplen for n = 2, ..., 9. These are defined as follows.package scalacase class Tuplen[+a1, ..., +an](1: a1, ..., n: an) { def toString = "(" ++ 1 ++ "," ++ . . . ++ "," ++ n ++ ") "}The implicitly imported Predef object (§12.5) defines the names Pair as an alias of Tuple2 and Triple as an alias for Tuple3.12.3.3 The Function ClassesScala defines function classes Functionn for n = 1, ..., 9. These are defined as fol-lows.package scala trait Functionn[-a1, ..., -an, +b] {def apply(x1: a1, ..., xn: an) : bdef toString = "<function>"}A subclass of Function1 represents partial functions, which are undefined on some points in their domain. In addition to the apply method of functions, partial func-tions also have a isDefined method, which tells whether the function is defined atthe given argument: class PartialFunction[-A, +B] extends Function1[A, B] {def isDefinedAt(x: A) : Boolean}-------------------------------------------------------------------------------12.3 Standard Reference Classes 147The implicitly imported Predef object (§12.5) defines the name Function as an aliasof Function1.12.3.4 Class ArrayThe class of generic arrays is given as follows. final class Array[A](len: Int) extends Seq[A] {def length: Int = lendef apply(i: Int) : A = . . .def update(i: Int, x: A) : Unit = . . .def elements: Iterator[A] = . . . def subArray(from: Int, end: Int) : Array[A] = . . .def filter(p: A => Boolean) : Array[A] = . . .def map[B](f: A => B) : Array[B] = . . .def flatMap[B](f: A => Array[B]) : Array[B] = . . . }If T is not a type parameter or abstract type, the type Array[T ] is represented as thenative array type []T in the underlying host system. In that case length returns thelength of the array, apply means subscripting, and update means element update. Because of the syntactic sugar for apply and update operations (§6.26,we have thefollowing correspondences between Scala and Java/C# code for operations on anarray xs:Scala Java/C#xs.lengthxs.lengthxs(i)xs[i]xs(i) = exs[i] = eArrays also implement the sequence trait scala.Seq by defining an elementsmethod which returns all elements of the array in an Iterator. Because of the tension between parametrized types in Scala and the ad-hoc imple-mentation of arrays in the host-languages, some subtle points need to be taken intoaccount when dealing with arrays. These are explained in the following. First, unlike arrays in Java or C#, arrays in Scala are not co-variant; That is, S <: Tdoes not imply Array[S] <: Array[T ] in Scala. However, it is possible to cast anarray of S to an array of T if such a cast is permitted in the host environment. For instance Array[String] does not conform to Array[Object], even thoughString conforms to Object. However, it is possible to cast an expression of typeArray[String] to Array[Object], and this cast will succeed without raising a ClassCastException. Example:val xs = new Array[String](2)// val ys: Array[Object] = xs// **** error: incompatible types------------------------------------------------------------------------------- 148The Scala Standard Libraryval ys: Array[Object] = xs.asInstanceOf[Array[Object]] // OKSecond, for polymorphic arrays, that have a type parameter or abstract type T astheir element type, a representation different from []T might be used. However, it is guaranteed that isInstanceOf and asInstanceOf still work as if the array used thestandard representation of monomorphic arrays:val ss = new Array[String](2)def f[T](xs: Array[T]) : Array[String] = if (xs.isInstanceOf[Array[String]]) xs.asInstanceOf[Array[String])else throw new Error("not an instance")f(ss)// returns ssThe representation chosen for polymorphic arrays also guarantees that polymor- phic array creations work as expected. An example is the following implementationof method mkArray, which creates an array of an arbitrary type T , given a sequenceof T 's which defines its elements. def mkArray[T](elems: Seq[T]) : Array[T] = {val result = new Array[T](elems.length)var i = 0for (elem <- elems) {result(i) = elemi += 1} }Note that under Java's erasure model of arrays the method above would not work asexpected ­ in fact it would always return an array of Object.Third, in a Java environment there is a method System.arraycopy which takes two objects as parameters together with start indices and a length argument, and copieselements from one object to the other, provided the objects are arrays of compatibleelement types. System.arraycopy will not work for Scala's polymorphic arrays be- cause of their different representation. One should instead use method Array.copywhich is defined in the companion object of class Array. This companion objectalso defines various constructor methods for arrays, as well as the extractor method unapplySeq (§8.1.8) which enables pattern matching over arrays.package scalaobject Array {/** copies array elements from `src' to `dest'. */def copy(src: AnyRef, srcPos: Int, dest: AnyRef, destPos: Int, length: Int) : Unit = . . .-------------------------------------------------------------------------------12.4 Class Node149/** Concatenate all argument arrays into a single array. */ def concat[T](xs: Array[T]*) : Array[T] = . . ./** Create a an array of successive integers. */def range(start: Int, end: Int) : Array[Int] = . . ./** Create an array with given elements. */ def apply[A <: AnyRef](xs: A*) : Array[A] = . . ./** Analogous to above. */def apply(xs: Boolean*) : Array[Boolean] = . . .def apply(xs: Byte*): Array[Byte]= . . . def apply(xs: Short*) : Array[Short]= . . .def apply(xs: Char*): Array[Char]= . . .def apply(xs: Int*): Array[Int]= . . .def apply(xs: Long*) : Array[Long]= . . .def apply(xs: Float*) : Array[Float]= . . .def apply(xs: Double*) : Array[Double] = . . .def apply(xs: Unit*): Array[Unit] = . . ./** Create an array containing several copies of an element. */def make[A](n: Int, elem: A) : Array[A] = {/** Enables pattern matching over arrays */def unapplySeq[A](x: Array[A]) : Option[Seq[A]] = Some(x) }Example 12.3.1 The following method duplicates a given argument array and re-turns a pair consisting of the original and the duplicate:def duplicate[T](xs: Array[T]) = {val ys = new Array[T](xs.length) Array.copy(xs, 0, ys, 0, xs.length)(xs, ys)}12.4Class Nodepackage scala.xmltrait Node {/** the label of this node */def label: String -------------------------------------------------------------------------------150The Scala Standard Library/** attribute axis */def attribute: Map[String, String] /** child axis (all children of this node) */def child: Seq[Node]/** descendant axis (all descendants of this node) */def descendant: Seq[Node] = child.toList.flatMap {x => x::x.descendant.asInstanceOf[List[Node]] }/** descendant axis (all descendants of this node) */def descendantorself: Seq[Node] = this::child.toList.flatMap {x => x::x.descendant.asInstanceOf[List[Node]]} override def equals(x: Any) : Boolean = x match {case that:Node =>that.label == this.label &&that.attribute.sameElements(this.attribute) &&that.child.sameElements(this.child) case _ => false}/** XPath style projection function. Returns all children of this node*that are labeled with 'that'. The document order is preserved. */ def \(that: Symbol) : NodeSeq = {new NodeSeq({that.name match {case "" => child.toListcase _ =>var res:List[Node] = Nil for (x <- child.elements if x.label == that.name) {res = x::res}res.reverse}})}/** XPath style projection function. Returns all nodes labeled with the *name 'that' from the 'descendantorself' axis. Document order is preserved.*/def \\(that: Symbol) : NodeSeq = {------------------------------------------------------------------------------- 12.4 Class Node151new NodeSeq(that.name match {case "" => this.descendantorselfcase _ => this.descendantorself.asInstanceOf[List[Node]]. filter(x => x.label == that.name)})}/** hashcode for this XML node */override def hashCode =Utility.hashCode(label, attribute.toList.hashCode, child) /** string representation of this node */override def toString = Utility.toXML(this)}-------------------------------------------------------------------------------152 The Scala Standard Library12.5The Predef ObjectThe Predef object defines standard functions and type aliases for Scala programs.It is always implicitly imported, so that all its defined members are available with- out qualification. Its definition for the JVM environment conforms to the followingsignature:package scalaobject Predef {// classOf --------------------------------------------------------- /** Returns the runtime representation of a class type. */def classOf[T]: Class[T] = null// this is a dummy, classOf is handled by compiler.// Standard type aliases --------------------------------------------- type String= java.lang.Stringtype Class[T]= java.lang.Class[T]// Miscellaneous -----------------------------------------------------type Function[-A, +B] = Function1[A, B] type Map[A, +B] = collection.immutable.Map[A, B]type Set[A] = collection.immutable.Set[A]val Map = collection.immutable.Mapval Set = collection.immutable.Set// Manifest types, companions, and incantations for summoning --------- type ClassManifest[T] = scala.reflect.ClassManifest[T]type Manifest[T]= scala.reflect.Manifest[T]type OptManifest[T]= scala.reflect.OptManifest[T]val ClassManifest = scala.reflect.ClassManifestval Manifest= scala.reflect.Manifestval NoManifest= scala.reflect.NoManifestdef manifest[T](implicit m: Manifest[T])= m def classManifest[T](implicit m: ClassManifest[T]) = mdef optManifest[T](implicit m: OptManifest[T])= m// Minor variations on identity functions ----------------------------- def identity[A](x: A) : A= x// @see `conforms` for the implicit version-------------------------------------------------------------------------------12.5 The Predef Object 153def implicitly[T](implicit e: T) = e// for summoning implicit values from the nether world@inline def locally[T](x: T) : T= x// to communicate intent and avoid unmoored statements // Asserts, Preconditions, Postconditions -----------------------------def assert(assertion: Boolean) {if (!assertion)throw new java.lang.AssertionError("assertion failed") }def assert(assertion: Boolean, message: => Any) {if (!assertion)throw new java.lang.AssertionError("assertion failed: " + message)}def assume(assumption: Boolean) { if (!assumption)throw new IllegalArgumentException("assumption failed")}def assume(assumption: Boolean, message: => Any) {if (!assumption)throw new IllegalArgumentException(message.toString) }def require(requirement: Boolean) {if (!requirement)throw new IllegalArgumentException("requirement failed")}def require(requirement: Boolean, message: => Any) { if (!requirement)throw new IllegalArgumentException("requirement failed: "+ message)}------------------------------------------------------------------------------- 154The Scala Standard Library// tupling ---------------------------------------------------------type Pair[+A, +B] = Tuple2[A, B]object Pair {def apply[A, B](x: A, y: B) = Tuple2(x, y) def unapply[A, B](x: Tuple2[A, B]) : Option[Tuple2[A, B]] = Some(x)}type Triple[+A, +B, +C] = Tuple3[A, B, C]object Triple {def apply[A, B, C](x: A, y: B, z: C) = Tuple3(x, y, z) def unapply[A, B, C](x: Tuple3[A, B, C]) : Option[Tuple3[A, B, C]] = Some(x)}// Printing and reading -----------------------------------------------def print(x: Any) = Console.print(x) def println() = Console.println()def println(x: Any) = Console.println(x)def printf(text: String, xs: Any*) = Console.printf(text.format(xs: *) )def readLine() : String = Console.readLine() def readLine(text: String, args: Any*) = Console.readLine(text, args)def readBoolean() = Console.readBoolean()def readByte() = Console.readByte()def readShort() = Console.readShort() def readChar() = Console.readChar()def readInt() = Console.readInt()def readLong() = Console.readLong()def readFloat() = Console.readFloat()def readDouble() = Console.readDouble() def readf(format: String) = Console.readf(format)def readf1(format: String) = Console.readf1(format)def readf2(format: String) = Console.readf2(format)def readf3(format: String) = Console.readf3(format) // Implict conversions ------------------------------------------------...}12.5.1 Predefined Implicit DefinitionsThe Predef object also contains a number of implicit definitions, which are avail- able by default (because Predef is implicitly imported) . Implicit definitions come in-------------------------------------------------------------------------------12.5 The Predef Object 155two priorities. High-priority implicits are defined in the Predef class itself whereaslow priority implicits are defined in a class inherited by Predef. The rules of staticoverloading resolution (§6.26.3) stipulate that, all other things being equal, implicit resolution prefers high-priority implicits over low-priority ones.The available low-priority implicits include definitions falling into the following cat-egories.1. For every primitive type, a wrapper that takes values of that type to instances of a runtime.Rich* class. For instance, values of type Int can be implicitlyconverted to instances of class runtime.RichInt.2. For every array type with elements of primitive type, a wrapper that takes the arrays of that type to instances of a runtime.WrappedArray class. For instance,values of type Array[Float] can be implicitly converted to instances of classruntime.WrappedArray[Float]. There are also generic array wrappers that take elements of type Array[T] for arbitrary T to WrappedArrays.3. An implicit conversion from String to WrappedString.The available high-priority implicits include definitions falling into the following categories.· An implicit wrapper that adds ensuring methods with the following over-loaded variants to type Any.def ensuring(cond: Boolean) : A = { assert(cond) ; x }def ensuring(cond: Boolean, msg: Any) : A = { assert(cond, msg) ; x } def ensuring(cond: A => Boolean) : A = { assert(cond(x) ); x }def ensuring(cond: A => Boolean, msg: Any) : A = { assert(cond(x) , msg) ; x }· An implicit wrapper that adds a -> method with the following implementation to type Any.def -> [B](y: B) : (A, B) = (x, y)· For every array type with elements of primitive type, a wrapper that takes thearrays of that type to instances of a runtime.ArrayOps class. For instance, values of type Array[Float] can be implicitly converted to instances of classruntime.ArrayOps[Float]. There are also generic array wrappers that takeelements of type Array[T] for arbitrary T to ArrayOpss. · An implicit wrapper that adds + and formatted method with the followingimplementations to type Any.def +(other: String) = String.valueOf(self) + otherdef formatted(fmtstr: String) : String = fmtstr format self -------------------------------------------------------------------------------156The Scala Standard Library· Numeric primitive conversions that implement the transitive closure of the following mappings:Byte-> ShortShort -> IntChar-> IntInt-> LongLong-> FloatFloat -> Double · Boxing and unboxing conversions between primitive types and their boxedversions:Byte<-> java.lang.ByteShort<-> java.lang.ShortChar <-> java.lang.CharacterInt<-> java.lang.IntegerLong<-> java.lang.LongFloat<-> java.lang.FloatDouble<-> java.lang.Double Boolean <-> java.lang.Boolean· An implicit definition that generates instances of type T <:< T, for any type T.Here, <:< is a class defined as follows.sealed abstract class <:<[-From, +To] extends (From => To) Implicit parameters of <:< types are typically used to implement type con-straints.-------------------------------------------------------------------------------Bibliography [Dra10]Iulian Dragos. Scala specialization, 2010. SID-9.[KP07]Andrew J. Kennedy and Benjamin C. Pierce. On Decidability of NominalSubtyping with Variance, January 2007. FOOL-WOOD '07. [Oa04]Martin Odersky and al. An Overview of the Scala Programming Lan-guage. Technical Report IC/2004/64, EPFL Lausanne, Switzerland, 2004.[OCRZ03] Martin Odersky, Vincent Cremet, Christine Röckl, and Matthias Zenger. A Nominal Theory of Objects with Dependent Types. In Proc. ECOOP'03,Springer LNCS, July 2003.[Ode06]Martin Odersky. The Scala Experiment ­ Can We Provide Better Lan-guage Support for Component Systems? In Proc. ACM Symposium on Principles of Programming Languages, 2006.[OZ05a]Martin Odersky and Matthias Zenger.Independently Extensible So-lutions to the Expression Problem. In Proc. FOOL 12, January 2005. http://homepages.inf.ed.ac.uk/wadler/fool.[OZ05b]Martin Odersky and Matthias Zenger. Scalable Component Abstractions. In Proc. OOPSLA, 2005. [W3C]W3C. Extensible Markup Language (XML) .http://www.w3.org/TR/REC-xml.------------------------------------------------------------------------------- -------------------------------------------------------------------------------Chapter AScala Syntax SummaryThe lexical syntax of Scala is given by the following grammar in EBNF form. upper::=`A' | · · · | `Z' | `$' | `' and Unicode category Lulower::=`a' | · · · | `z' and Unicode category Llletter ::=upper | lower and Unicode categories Lo, Lt, Nldigit::=`0' | · · · | `9'opchar::="all other characters in \u0020-007F and Unicode categories Sm, So except parentheses ([]) and periods"op::=opchar {opchar}varid::=lower idrestplainid::=upper idrest |varid|opid::=plainid|`\`' stringLit `\`'idrest::={letter | digit} [`' op] integerLiteral::=(decimalNumeral | hexNumeral | octalNumeral) [`L' | `l']decimalNumeral::=`0' | nonZeroDigit {digit}hexNumeral::= `0' `x' hexDigit {hexDigit}octalNumeral::=`0' octalDigit {octalDigit}digit::=`0' | nonZeroDigitnonZeroDigit::= `1' | · · · | `9'octalDigit::=`0' | · · · | `7'floatingPointLiteral::=digit {digit} `.' {digit} [exponentPart] [floatType] |`.' digit {digit} [exponentPart] [floatType]|digit {digit} exponentPart [floatType]|digit {digit} [exponentPart] floatTypeexponentPart::= (`E' | `e') [`+' | `-'] digit {digit}floatType::=`F' | `f' | `D' | `d'------------------------------------------------------------------------------- 160Scala Syntax SummarybooleanLiteral::=`true' | `false'characterLiteral ::=`\'' printableChar `\''|`\'' charEscapeSeq `\'' stringLiteral::=`"' {stringElement} `"'|`"""' multiLineChars `"""'stringElement::= printableCharNoDoubleQuote |charEscapeSeqmultiLineChars::={[`"'] [`"'] charNoDoubleQuote} {`"'}symbolLiteral::=`'' plainid comment::=`/*' "any sequence of characters" `*/'|`//' "any sequence of characters up to end of line"nl::="new line character" semi::=`;' |nl {nl}The context-free syntax of Scala is given by the following EBNF grammar.Literal::=[`-'] integerLiteral |[`-'] floatingPointLiteral|booleanLiteral|characterLiteral|stringLiteral|symbolLiteral|`null' QualId::=id {`.' id}ids::=id {`,' id}Path::=StableId|[id `.'] `this'StableId ::=id|Path `.' id|[id '.'] `super' [ClassQualifier] `.' idClassQualifier::=`[' id `]'Type ::=FunctionArgTypes `=>' Type|InfixType [ExistentialClause]FunctionArgTypes::= InfixType| `(' [ ParamType {`,' ParamType } ] `) ' ExistentialClause ::=`forSome' `{' ExistentialDcl {semi ExistentialDcl} `}'ExistentialDcl::=`type' TypeDcl|`val' ValDcl InfixType::=CompoundType {id [nl] CompoundType}CompoundType::=AnnotType {`with' AnnotType} [Refinement]------------------------------------------------------------------------------- 161|RefinementAnnotType::=SimpleType {Annotation}SimpleType::=SimpleType TypeArgs|SimpleType `#' id |StableId|Path `.' `type'|`(' Types ') 'TypeArgs::=`[' Types `]'Types::= Type {`,' Type}Refinement::=[nl] `{' RefineStat {semi RefineStat} `}'RefineStat::=Dcl|`type' TypeDef | TypePat::=TypeAscription::=`:' InfixType|`:' Annotation {Annotation}|`:' `' `*'Expr ::=(Bindings | [`implicit'] id | `') `=>' Expr|Expr1Expr1::=`if' `(' Expr `) ' {nl} Expr [[semi] else Expr]| `while' `(' Expr `) ' {nl} Expr|`try' `{' Block `}' [`catch'`{' CaseClauses `}'][`finally' Expr]|`do' Expr [semi] `while' `(' Expr ') ' |`for' (`(' Enumerators `) ' | `{' Enumerators `}'){nl} [`yield'] Expr|`throw' Expr|`return' [Expr]| [SimpleExpr `.'] id `=' Expr|SimpleExpr1 ArgumentExprs `=' Expr|PostfixExpr|PostfixExpr Ascription|PostfixExpr `match' `{' CaseClauses `}' PostfixExpr::=InfixExpr [id [nl]]InfixExpr::=PrefixExpr|InfixExpr id [nl] InfixExprPrefixExpr::=[`-' | `+' | `~' | `!'] SimpleExpr SimpleExpr::=`new' (ClassTemplate | TemplateBody)|BlockExpr|SimpleExpr1 [`']SimpleExpr1::=Literal | Path|`'|`(' [Exprs] `) '|SimpleExpr `.' id|SimpleExpr TypeArgs|SimpleExpr1 ArgumentExprs -------------------------------------------------------------------------------162Scala Syntax Summary|XmlExprExprs::=Expr {`,' Expr} ArgumentExprs::=`(' [Exprs] `) '|`(' [Exprs `,'] PostfixExpr `:' `' `*' ') '|[nl] BlockExprBlockExpr ::=`{' CaseClauses `}'|`{' Block `}'Block::={BlockStat semi} [ResultExpr]BlockStat::=Import |{Annotation} [`implicit' | `lazy'] Def|{Annotation} {LocalModifier} TmplDef|Expr1|ResultExpr::=Expr1| (Bindings | ([`implicit'] id | `') `:' CompoundType) `=>' BlockEnumerators::=Generator {semi Enumerator}Enumerator::=Generator |Guard|`val' Pattern1 `=' ExprGenerator::=Pattern1 `<-' Expr [Guard]CaseClauses::=CaseClause { CaseClause } CaseClause::=`case' Pattern [Guard] `=>' BlockGuard::=`if' PostfixExprPattern::=Pattern1 { `|' Pattern1 } Pattern1::=varid `:' TypePat|`' `:' TypePat|Pattern2Pattern2::=varid [`@' Pattern3]| Pattern3Pattern3::=SimplePattern|SimplePattern { id [nl] SimplePattern }SimplePattern::=`'|varid |Literal|StableId|StableId `(' [Patterns `) '|StableId `(' [Patterns `,'] [varid `@'] `' `*' `) ' |`(' [Patterns] `) '|XmlPatternPatterns::=Pattern [`,' Patterns]|`' *TypeParamClause::= `[' VariantTypeParam {`,' VariantTypeParam} `]'FunTypeParamClause::=`[' TypeParam {`,' TypeParam} `]'VariantTypeParam::={Annotation} [`+' | `-'] TypeParam TypeParam::=(id | `') [TypeParamClause] [`>:' Type] [`<:' Type]-------------------------------------------------------------------------------163 {`<%' Type} {`:' Type}ParamClauses::={ParamClause} [[nl] `(' `implicit' Params `) ']ParamClause::=[nl] `(' [Params] ') ' Params::=Param {`,' Param}Param::={Annotation} id [`:' ParamType] [`=' Expr]ParamType::=Type| `=>' Type |Type `*'ClassParamClauses ::={ClassParamClause}[[nl] `(' `implicit' ClassParams `) ']ClassParamClause::=[nl] `(' [ClassParams] ') ' ClassParams::=ClassParam {`' ClassParam}ClassParam::={Annotation} [{Modifier} (`val' | `var') ]id `:' ParamType [`=' Expr] Bindings::=`(' Binding {`,' Binding `) 'Binding::=(id | `') [`:' Type]Modifier::=LocalModifier| AccessModifier|`override'LocalModifier::=`abstract'|`final'|`sealed'|`implicit' |`lazy'AccessModifier::=(`private' | `protected') [AccessQualifier]AccessQualifier::=`[' (id | `this') `]' Annotation::=`@' SimpleType {ArgumentExprs}ConstrAnnotation::=`@' SimpleType ArgumentExprsNameValuePair::=`val' id `=' PrefixExpr TemplateBody::=[nl] `{' [SelfType] TemplateStat {semi TemplateStat} `}'TemplateStat::=Import|{Annotation [nl]} {Modifier} Def |{Annotation [nl]} {Modifier} Dcl|Expr|SelfType::=id [`:' Type] `=>'|`this' `:' Type `=>' Import::=`import' ImportExpr {`,' ImportExpr}ImportExpr::=StableId `.' (id | `' | ImportSelectors)ImportSelectors::= `{' {ImportSelector `,'} (ImportSelector | `') `}'ImportSelector::=id [`=>' id | `=>' `']Dcl::=`val' ValDcl |`var' VarDcl|`def' FunDcl-------------------------------------------------------------------------------164Scala Syntax Summary| `type' {nl} TypeDclValDcl::=ids `:' TypeVarDcl::=ids `:' TypeFunDcl::=FunSig [`:' Type]FunSig ::=id [FunTypeParamClause] ParamClausesTypeDcl::=id [TypeParamClause] [`>:' Type] [`<:' Type]PatVarDef::=`val' PatDef |`var' VarDefDef::=PatVarDef|`def' FunDef|`type' {nl} TypeDef|TmplDefPatDef ::=Pattern2 {`,' Pattern2} [`:' Type] `=' ExprVarDef::=PatDef|ids `:' Type `=' `'FunDef::=FunSig [`:' Type] `=' Expr |FunSig [nl] `{' Block `}'|`this' ParamClause ParamClauses(`=' ConstrExpr | [nl] ConstrBlock)TypeDef::=id [TypeParamClause] `=' Type TmplDef::=[`case'] `class' ClassDef|[`case'] `object' ObjectDef|`trait' TraitDefClassDef::=id [TypeParamClause] {ConstrAnnotation} [AccessModifier] ClassParamClauses ClassTemplateOptTraitDef::=id [TypeParamClause] TraitTemplateOptObjectDef::=id ClassTemplateOptClassTemplateOpt ::=`extends' ClassTemplate | [[`extends'] TemplateBody]TraitTemplateOpt::=`extends' TraitTemplate | [[`extends'] TemplateBody]ClassTemplate ::=[EarlyDefs] ClassParents [TemplateBody]TraitTemplate::=[EarlyDefs] TraitParents [TemplateBody]ClassParents::=Constr {`with' AnnotType} TraitParents::=AnnotType {`with' AnnotType}Constr::=AnnotType {ArgumentExprs}EarlyDefs::= `{' [EarlyDef {semi EarlyDef}] `}' `with' EarlyDef::={Annotation [nl]} {Modifier} PatVarDefConstrExpr::=SelfInvocation|ConstrBlockConstrBlock::=`{' SelfInvocation {semi BlockStat} `}' SelfInvocation::=`this' ArgumentExprs {ArgumentExprs}TopStatSeq::=TopStat {semi TopStat}TopStat::={Annotation [nl]} {Modifier} TmplDef |Import|Packaging-------------------------------------------------------------------------------165|PackageObject|Packaging ::=`package' QualId [nl] `{' TopStatSeq `}'PackageObject::=`package' `object' ObjectDefCompilationUnit::={`package' QualId semi} TopStatSeq --------------------------------------------------------------------------------------------------------------------------------------------------------------Chapter BChange Log Changes in Version 2.8.0Trailing commasTrailing commas in expression, argument, type or pattern sequences are no longersupported.Changes in Version 2.8 (under development) Changed visibility rules for nested packages (where done?)Changed visibility rules in §2so that packages are no longer treated specially.Added section §3.5.3on weak conformance. Relaxed type rules for conditionals, match expressions, try expressions to compute their result type using least upperbound wrt weak conformance. Relaxed type rule for local type inference so that ar-gument types need only weekly conform to inferred formal parameter types. Added section on numeric widening in §6.26to support weak conformance.Tightened rules to avpod accidential overrides in §5.1.4.Removed class literals.Added section §7.4on context bounds. Clarified differences between isInstanceOf and pattern matches (§12.1) .Allowed implicit modifier on function literals with a single parameter (§6.23) .------------------------------------------------------------------------------- 168Change LogChanges in Version 2.7.2 (10-Nov-2008Precedence of Assignment OperatorsThe precedence of assignment operators has been brought in line with Java's (§6.12) .From now on, += has the same precedence as =.Wildcards as function parametersA formal parameter to an anonymous fucntion may now be a wildcard representedby an underscore (§6.23) .Example: _ => 7// The function that ignores its argument// and always returns 7.Unicode alternative for left arrowThe Unicode glyph \u2190 `' is now treated as a reserved identifier, equivalent to the ASCII symbol `<-'.Changes in Version 2.7.1 (09-April-2008)Change in Scoping Rules for Wildcard Placeholders in TypesA wildcard in a type now binds to the closest enclosing type application. For exam- ple List[List[]] is now equivalent to the existential typeList[List[t] forSome { type t }] .In version 2.7.0, the type expanded instead toList[List[t]] forSome { type t } . The new convention corresponds exactly to the way wildcards in Java are inter-preted.No Contractiveness Requirement for ImplicitsThe contractiveness requirement for implicit method definitions has been dropped. Instead it is checked for each implicit expansion individually that the expansiondoes not result in a cycle or a tree of infinitely growing types (§7.2) .------------------------------------------------------------------------------- 169Changes in Version 2.7.0 (07-Feb-2008)Java GenericsScala now supports Java generic types by default:· A generic type in Java such as ArrayList<String> is translated to a generic type in Scala: ArrayList[String].· A wildcard type such as ArrayList<? extends Number> is translated toArrayList[_ <: Number]. This is itself a shorthand for the existential type ArrayList[T] forSome { type T <: Number }.· A raw type in Java such as ArrayList is translated to ArrayList[], which is ashorthand for ArrayList[T] forSome { type T }.This translation works if -target:jvm-1.5 is specified, which is the new default. For any other target, Java generics are not recognized. To ensure upgradability of Scalacodebases, extraneous type parameters for Java classes under -target:jvm-1.4are simply ignored. For instance, when compiling with -target:jvm-1.4, a Scala type such as ArrayList[String] is simply treated as the unparameterized typeArrayList.Changes to Case ClassesThe Scala compiler generates now for every case class a companion extractor object (§5.3.2) .For instance, given the case class:case class X(elem: String)the following companion object is generated:object X {def unapply(x: X) : Some[String] = Some(x.elem) def apply(s: String) : X = new X(s)}If the object exists already, only the apply and unapply methods are added to it.Three restrictions on case classes have been removed.1. Case classes can now inherit from other case classes. 2. Case classes may now be abstract.3. Case classes may now come with companion objects.-------------------------------------------------------------------------------170Change Log Changes in Version 2.6.1 (30-Nov-2007)Mutable variables introduced by pattern bindingMutable variables can now be introduced by a pattern matching definition (§4.2) ,just like values can. Examples: var (x, y) = if (positive) (1, 2) else (-1, -3)var hd :: tl = mylistSelf-typesSelf types can now be introduced without defining an alias name for this (§5.1) .Example: class C {type T <: Traittrait Trait { this: T => ... }}Changes in Version 2.6 (27-July-2007)Existential typesIt is now possible to define existential types (§3.2.10) .An existential type has the form T forSome {Q} where Q is a sequence of value and/or type declarations. Giventhe class definitionsclass Ref[T]abstract class Outer { type T }one may for example write the following existential types Ref[T] forSome { type T <: java.lang.Number }Ref[x.T] forSome { val x: Outer }Lazy valuesIt is now possible to define lazy value declarations using the new modifier lazy (§4.1) .A lazy value definition evaluates its right hand side e the first time the valueis accessed. Example:import compat.Platform._val t0 = currentTimelazy val t1 = currentTime -------------------------------------------------------------------------------171val t2 = currentTimeprintln("t0 <= t2: " + (t0 <= t2) )//trueprintln("t1 <= t2: " + (t1 <= t2) ) //false (lazy evaluation of t1)Structural typesIt is now possible to declare structural types using type refinements (§3.2.7) .Forexample:class File(name: String) { def getName() : String = namedef open() { /*..*/ }def close() { println("close file") }}def test(f: { def getName() : String }) { println(f.getName) }test(new File("test.txt") ) test(new java.io.File("test.txt") )There's also a shorthand form for creating values of structural types. For instance,new { def getName() = "aaron" }is a shorthand for new AnyRef{ def getName() = "aaron" }Changes in Version 2.5 (02-May-2007)Type constructor polymorphism1Type parameters (§4.4) and abstract type members (§4.3) can now also abstract over type constructors (§3.3.3) .This allows a more precise Iterable interface:trait Iterable[+T] {type MyType[+T] <: Iterable[T] // MyType is a type constructordef filter(p: T => Boolean) : MyType[T] = ... def map[S](f: T => S) : MyType[S] = ...}1Implemented by Adriaan Moors-------------------------------------------------------------------------------172Change Log abstract class List[+T] extends Iterable[T] {type MyType[+T] = List[T]}This definition of Iterable makes explicit that mapping a function over a certainstructure (e.g., a List) will yield the same structure (containing different elements) . Early object initializationIt is now possible to initialize some fields of an object before any parent constructorsare called (§5.1.6) .This is particularly useful for traits, which do not have normal constructor parameters. Example:trait Greeting {val name: Stringval msg = "How are you, "+name}class C extends {val name = "Bob" } with Greeting {println(msg)}In the code above, the field name is initialized before the constructor of Greetingis called.Therefore, field msg in class Greeting is properly initialized to "How are you, Bob".For-comprehensions, revisedThe syntax of for-comprehensions has changed (§6.19) .In the new syntax, gener-ators do not start with a val anymore, but filters start with an if (and are called guards) . A semicolon in front of a guard is optional. For example:for (val x <- List(1, 2, 3) ; x % 2 == 0) println(x)is now writtenfor (x <- List(1, 2, 3) if x % 2 == 0) println(x) The old syntax is still available but will be deprecated in the future.Implicit anonymous functionsIt is now possible to define anonymous functions using underscores in parameterposition (§Example 6.23.1) .For instance, the expressions in the left column are each function values which expand to the anonymous functions on their right.-------------------------------------------------------------------------------173_ + 1x => x + 1 _ * _(x1, x2) => x1 * x2(: int) * 2(x: int) => (x: int) * 2if () x else yz => if (z) x else y.map(f)x => x.map(f).map(_ + 1) x => x.map(y => y + 1)As a special case (§6.7) ,a partially unapplied method is now designated m _ insteadof the previous notation &m.The new notation will displace the special syntax forms .m() for abstracting over method receivers and &m for treating an unapplied method as a function value. Forthe time being, the old syntax forms are still available, but they will be deprecatedin the future. Pattern matching anonymous functions, refinedIt is now possible to use case clauses to define a function value directly for functionsof arities greater than one (§8.5) .Previously, only unary functions could be defined that way. Example:def scalarProduct(xs: Array[Double], ys: Array[Double]) =(0.0 /: (xs zip ys) ) {case (a, (b, c) ) => a + b * c}Changes in Version 2.4 (09-Mar-2007) Object-local private and protectedThe private and protected modifiers now accept a [this] qualifier (§5.2) .A defini-tion M which is labelled private[this] is private, and in addition can be accessed only from within the current object. That is, the only legal prefixes for M are thisor C .this. Analogously, a definition M which is labelled protected[this] is pro-tected, and in addition can be accessed only from within the current object. Tuples, revisedThe syntax for tuples has been changed from {. . .} to (. . .) (§6.9) .For any sequence oftypes T1, ..., Tn,(T1, ..., Tn)is a shorthand forTuplen[T1, . . . , Tn]. Analogously, for any sequence of expressions or patterns x1, ..., xn,(x1, ..., xn)is a shorthand forTuplen(x1, . . . , xn) .------------------------------------------------------------------------------- 174Change LogAccess modifiers for primary constructorsThe primary constructor of a class can now be marked private or protected (§5.3) .If such an access modifier is given, it comes between the name of the class and its value parameters. Example:class C[T] private (x: T) { ... }AnnotationsThe support for attributes has been extended and its syntax changed (§11) .At-tributes are now called annotations. The syntax has been changed to follow Java's conventions, e.g. @attribute instead of [attribute]. The old syntax is still avail-able but will be deprecated in the future.Annotations are now serialized so that they can be read by compile-time or run- time tools. Class scala.Annotation has two sub-traits which are used to indicatehow annotations are retained. Instances of an annotation class inheriting from traitscala.ClassfileAnnotation will be stored in the generated class files. Instances of an annotation class inheriting from trait scala.StaticAnnotation will be visibleto the Scala type-checker in every compilation unit where the annotated symbol isaccessed.Decidable subtyping The implementation of subtyping has been changed to prevent infinite recursions.Termination of subtyping is now ensured by a new restriction of class graphs to befinitary (§5.1.5) .Case classes cannot be abstract It is now explicitly ruled out that case classes can be abstract (§5.2) .The specifica-tion was silent on this point before, but did not explain how abstract case classeswere treated. The Scala compiler allowed the idiom. New syntax for self aliases and self typesIt is now possible to give an explicit alias name and/or type for the self referencethis (§5.1) .For instance, inclass C { self: D => ...}the name self is introduced as an alias for this within C and the self type (§5.3) of Cis assumed to be D. This construct is introduced now in order to replace eventually -------------------------------------------------------------------------------175both the qualified this construct C.this and the requires clause in Scala.Assignment Operators It is now possible to combine operators with assignments (§6.12.4) .Example: var x: int = 0x += 1Changes in Version 2.3.2 (23-Jan-2007)ExtractorsIt is now possible to define patterns independently of case classes, using unapplymethods in extractor objects (§8.1.8) .Here is an example: object Twice {def apply(x:Int) : int = x*2def unapply(z:Int) : Option[int] = if (z%2==0) Some(z/2) else None}val x = Twice(21)x match { case Twice(n) => Console.println(n) } // prints 21 In the example, Twice is an extractor object with two methods:· The apply method is used to build even numbers.· The unapply method is used to decompose an even number; it is in a sense the reverse of apply. unapply methods return option types: Some(...) for amatch that suceeds, None for a match that fails. Pattern variables are returnedas the elements of Some. If there are several variables, they are grouped in a tuple.In the second-to-last line, Twice's apply method is used to construct a number x.In the last line, x is tested against the pattern Twice(n) . This pattern succeeds foreven numbers and assigns to the variable n one half of the number that was tested. The pattern match makes use of the unapply method of object Twice. More detailson extractors can be found in the paper "Matching Objects with Patterns" by Emir,Odersky and Williams. TuplesA new lightweight syntax for tuples has been introduced (§6.9) .For any sequence oftypes T1, ..., Tn,{T1, ..., Tn}is a shorthand forTuplen[T1, . . . , Tn]. -------------------------------------------------------------------------------176Change LogAnalogously, for any sequence of expressions or patterns x1, ..., xn,{x1, ..., xn} is a shorthand forTuplen(x1, . . . , xn) .Infix operators of greater aritiesIt is now possible to use methods which have more than one parameter as infixoperators (§6.12) .In this case, all method arguments are written as a normal pa- rameter list in parentheses. Example:class C {def +(x: int, y: String) = ...}val c = new Cc + (1, "abc")Deprecated attributeA new standard attribute deprecated is available (§11) .If a member definition is marked with this attribute, any reference to the member will cause a "deprecated"warning message to be emitted.Changes in Version 2.3 (23-Nov-2006)ProceduresA simplified syntax for functions returning unit has been introduced (§4.6.3) .Scala now allows the following shorthands:def f(params)fordef f(params) : unitdef f(params) { ... }fordef f(params) : unit = { ... }Type Patterns The syntax of types in patterns has been refined (§8.2) .Scala now distinguishes be-tween type variables (starting with a lower case letter) and types as type argumentsin patterns. Type variables are bound in the pattern. Other type arguments are, as in previous versions, erased. The Scala compiler will now issue an "unchecked"warning at places where type erasure might compromise type-safety.Standard TypesThe recommended names for the two bottom classes in Scala's type hierarchy have changed as follows:-------------------------------------------------------------------------------177All==>NothingAllRef==> NullThe old names are still available as type aliases.Changes in Version 2.1.8 (23-Aug-2006)Visibility Qualifier for protectedProtectedmemberscan nowhaveavisibilityqualifier(§5.2) ,e.g.protected[<qualifier>]. In particular, one can now simulate package protectedaccess as in Java writing protected[P] def X ...where P would name the package containing X.Relaxation of Private AcessPrivate members of a class can now be referenced from the companion module ofthe class and vice versa (§5.2) Implicit LookupThe lookup method for implicit definitions has been generalized (§7.2) .Whensearching for an implicit definition matching a type T , now are considered1. all identifiers accessible without prefix, and 2. all members of companion modules of classes associated with T .(The second clause is more general than before) . Here, a class is associated with atype T if it is referenced by some part of T , or if it is a base class of some part of T . For instance, to find implicit members corresponding to the typeHashSet[List[Int], String]one would now look in the companion modules (aka static parts) of HashSet, List,Int, and String. Before, it was just the static part of HashSet. Tightened Pattern MatchA typed pattern match with a singleton type p.type now tests whether the selectorvalue is reference-equal to p (§8.1) .Example:val p = List(1, 2, 3) ------------------------------------------------------------------------------- 178Change Logval q = List(1, 2)val r = qr match {case : p.type => Console.println("p")case : q.type => Console.println("q") }This will match the second case and hence will print "q". Before, the singleton typeswere erased to List, and therefore the first case would have matched, which is non-sensical. Changes in Version 2.1.7 (19-Jul-2006)Multi-Line string literalsIt is now possible to write multi-line string-literals enclosed in triple quotes (§1.3.5) .Example:"""this is a multi-linestring literal"""No escape substitutions except for unicode escapes are performed in such stringliterals.Closure SyntaxThe syntax of closures has been slightly restricted (§6.23) .The form x: T => Eis valid only when enclosed in braces, i.e. { x: T => E }. The following is illegal,because it might be read as the value x typed with the type T => E:val f = x: T => E Legal alternatives are:val f = { x: T => E }val f = (x: T) => E-------------------------------------------------------------------------------179Changes in Version 2.1.5 (24-May-2006) Class LiteralsThere is a new syntax for class literals (§6.2) :For any class type C , classOf[C ] des-ignates the run-time representation of C .Changes in Version 2.0 (12-Mar-2006) Scala in its second version is different in some details from the first version of thelanguage. There have been several additions and some old idioms are no longersupported. This appendix summarizes the main changes. New KeywordsThe following three words are now reserved; they cannot be used as identifiers (§1.1)implicitmatchrequiresNewlines as Statement Separators Newlines can now be used as statement separators in place of semicolons (§1.2)Syntax RestrictionsThere are some other situations where old constructs no longer work:Pattern matching expressions. The match keyword now appears only as infix op-erator between a selector expression and a number of cases, as in:expr match {case Some(x) => ...case None => ... }Variants such as expr.match {...} or just match {...} are no longer sup-ported."With" in extends clauses.. The idiomclass C with M { ... } is no longer supported. A with connective is only allowed following an extends clause. For instance, the line above would have to be written-------------------------------------------------------------------------------180Change Logclass C extends AnyRef with M { ... } . However, assuming M is a trait (see 5.3.3) ,it is also legal to writeclass C extends M { ... }The latter expression is treated as equivalent toclass C extends S with M { ... } where S is the superclass of M.Regular Expression Patterns.The only form of regular expression pattern that iscurrently supported is a sequence pattern, which might end in a sequence wildcard *. Example:case List(1, 2, *) => ... // will match all lists starting with \code{1,2}.It is at current not clear whether this is a permanent restriction. We are evaluatingthe possibility of re-introducing full regular expression patterns in Scala. Selftype AnnotationsThe recommended syntax of selftype annotations has changed.class C: T extends B { ... }becomesclass C requires T extends B { ... }That is, selftypes are now indicated by the new requires keyword. The old syntax is still available but is considered deprecated.For-comprehensionsFor-comprehensions (§6.19) now admit value and pattern definitions. Example:for {val x <- List.range(1, 100) val y <- List.range(1, x)val z = x + yisPrime(z)} yield Pair(x, y)Note the definition val z = x + y as the third item in the for-comprehension.------------------------------------------------------------------------------- 181ConversionsThe rules for implicit conversions of methods to functions (§6.26) have been tight-ened. Previously, a parameterized method used as a value was always implicitly converted to a function. This could lead to unexpected results when method argu-ments where forgotten. Consider for instance the statement below:show(x.toString)where show is defined as follows: def show(x: String) = Console.println(x) .Most likely, the programmer forgot to supply an empty argument list () to toString.The previous Scala version would treat this code as a partially applied method, and expand it to:show(() => x.toString() )As a result, the address of a closure would be printed instead of the value of s.Scala version 2.0 will apply a conversion from partially applied method to function value only if the expected type of the expression is indeed a function type. For in-stance, the conversion would not be applied in the code above because the expectedtype of show's parameter is String, not a function type. The new convention disallows some previously legal code. Example:def sum(f: int => double) (a: int, b: int) : double =if (a > b) 0 else f(a) + sum(f) (a + 1, b)val sumInts =sum(x => x)// error: missing argumentsThe partial application of sum in the last line of the code above will not be convertedto a function type. Instead, the compiler will produce an error message which states that arguments for method sum are missing. The problem can be fixed by providingan expected type for the partial application, for instance by annotating the defini-tion of sumInts with its type: val sumInts: (int, int) => double=sum(x => x)// OKOn the other hand, Scala version 2.0 now automatically applies methods with emptyparameter lists to () argument lists when necessary. For instance, the show expres- sion above will now be expanded toshow(x.toString() ) .Scala version 2.0 also relaxes the rules of overriding with respect to empty parameterlists. The revised definition of matching members (§5.1.3) makes it now possible to -------------------------------------------------------------------------------182Change Logoverride a method with an explicit, but empty parameter list () with a parameterless method, and vice versa. For instance, the following class definition is now legal:class C {override def toString: String = ...}Previously this definition would have been rejected, because the toString method as inherited from java.lang.Object takes an empty parameter list.Class ParametersA class parameter may now be prefixed by val or var (§5.3) .Private QualifiersPreviously, Scala had three levels of visibility: private, protected and public. There was no way to restrict accesses to members of the current package, as in Java. Scala2 now defines access qualifiers that let one express this level of visibility, amongothers. In the definition private[C] def f(...)access to f is restricted to all code within the class or package C (which must containthe definition of f) (§5.2)Changes in the Mixin ModelThe model which details mixin composition of classes has changed significantly. The main differences are:1. We now distinguish between traits that are used as mixin classes and normalclasses. The syntax of traits has been generalized from version 1.0, in thattraits are now allowed to have mutable fields. However, as in version 1.0, traits still may not have constructor parameters.2. Member resolution and super accesses are now both defined in terms of aclass linearization.3. Scala's notion of method overloading has been generalized; in particular, it is now possible to have overloaded variants of the same method in a subclassand in a superclass, or in several different mixins. This makes method over-loading in Scala conceptually the same as in Java. The new mixin model is explained in more detail in §5.-------------------------------------------------------------------------------183Implicit ParametersViews in Scala 1.0 have been replaced by the more general concept of implicit pa- rameters (§7)Flexible Typing of Pattern MatchingThe new version of Scala implements more flexible typing rules when it comes topattern matching over heterogeneous class hierarchies (§8.4) .A heterogeneous class hierarchy is one where subclasses inherit a common superclass with different pa-rameter types. With the new rules in Scala version 2.0 one can perform patternmatches over such hierarchies with more precise typings that keep track of the infor- mation gained by comparing the types of a selector and a matching pattern (§Exam-ple 8.4.1) .This gives Scala capabilities analogous to guarded algebraic data types.-------------------------------------------------------------------------------

D Do oc cu um me en nt t O Ou ut tl li in ne e

* Lexical Syntax
  o Identifiers  o Newline Characters   o Literals
    # Integer Literals    # Floating Point Literals    # Boolean Literals    # Character Literals    # String Literals    # Escape Sequences     # Symbol literals
  o Whitespace and Comments  o XML mode
* Identifiers, Names and Scopes* Types
  o Paths   o Value Types
    # Singleton Types    # Type Projection    # Type Designators    # Parameterized Types    # Tuple Types    # Annotated Types     # Compound Types    # Infix Types    # Function Types    # Existential Types
  o Non-Value Types
    # Method Types    # Polymorphic Method Types     # Type Constructors
  o Base Types and Member Definitions  o Relations between types
    # Type Equivalence    # Conformance    # Weak Conformance
  o Volatile Types  o Type Erasure
* Basic Declarations and Definitions
  o Value Declarations and Definitions  o Variable Declarations and Definitions   o Type Declarations and Type Aliases  o Type Parameters  o Variance Annotations  o Function Declarations and Definitions
    # By-Name Parameters     # Repeated Parameters    # Procedures    # Method Return Type Inference
  o Import Clauses
* Classes and Objects
  o Templates
    # Constructor Invocations    # Class Linearization    # Class Members    # Overriding    # Inheritance Closure    # Early Definitions
  o Modifiers  o Class Definitions
    # Constructor Definitions    # Case Classes    # Traits
  o Object Definitions
* Expressions
  o Expression Typing  o Literals  o The Null Value  o Designators  o This and Super  o Function Applications
    # Named and Default Arguments
  o Method Values  o Type Applications  o Tuples  o Instance Creation Expressions  o Blocks   o Prefix, Infix, and Postfix Operations
    # Prefix Operations    # Postfix Operations    # Infix Operations    # Assignment Operators
  o Typed Expressions  o Annotated Expressions  o Assignments  o Conditional Expressions  o While Loop Expressions  o Do Loop Expressions  o For Comprehensions and For Loops   o Return Expressions  o Throw Expressions  o Try Expressions  o Anonymous Functions  o Constant Expressions  o Statements  o Implicit Conversions
    # Value Conversions    # Method Conversions    # Overloading Resolution    # Local Type Inference    # Eta Expansion

* Implicit Parameters and Views
  o The Implicit Modifier  o Implicit Parameters  o Views  o Context Bounds and View Bounds  o Manifests
* Pattern Matching
  o Patterns
    # Variable Patterns    # Typed Patterns    # Pattern Binders    # Literal Patterns    # Stable Identifier Patterns     # Constructor Patterns    # Tuple Patterns    # Extractor Patterns    # Pattern Sequences    # Infix Operation Patterns    # Pattern Alternatives     # XML Patterns     # Regular Expression Patterns    # Irrefutable Patterns
  o Type Patterns  o Type Parameter Inference in Patterns  o Pattern Matching Expressions   o Pattern Matching Anonymous Functions
* Top-Level Definitions
  o Compilation Units  o Packagings  o Package Objects  o Package References   o Programs
* XML expressions and patterns
  o XML expressions  o XML patterns
* User-Defined Annotations* The Scala Standard Library
  o Root Classes  o Value Classes
    # Numeric Value Types    # Class [flexiblecolumns=true,basicstyle=]£Boolean£    # Class [flexiblecolumns=true,basicstyle=]£Unit£
  o Standard Reference Classes
    # Class [flexiblecolumns=true,basicstyle=]£String£    # The [flexiblecolumns=true,basicstyle=]£Tuple£ classes    # The [flexiblecolumns=true,basicstyle=]£Function£ Classes     # Class [flexiblecolumns=true,basicstyle=]£Array£
  o Class Node  o The [flexiblecolumns=true,basicstyle=]£Predef£ Object
    # Predefined Implicit Definitions

* Scala Syntax Summary* Change Log
-------------------------------------------------------------------------------



--
Viktor Klang

Akka Tech LeadTypesafe - Enterprise-Grade Scala from the Experts

Twitter: @viktorklang
Donald McLean
Joined: 2009-11-11,
User offline. Last seen 2 years 48 weeks ago.
Re: Text version of Scala Language Specification

Calibre is your friend.

http://calibre-ebook.com/

On Wed, Dec 21, 2011 at 1:58 PM, Paul Phillips wrote:
>
> I don't intend to do this again, so the language is frozen right there for
> all eternity unless someone else wants to make this less of a one-shot thing
> and/or tell me how to accomplish the same thing on OSX with less manual
> intervention.

Simon Ochsenreither
Joined: 2011-07-17,
User offline. Last seen 42 years 45 weeks ago.
Re: Text version of Scala Language Specification
Thanks!

Is it possible to put this into docs.scala-lang.org?

I wouldn't mind keeping it up to date as long as I don't have to chase the changes ...

Bye
d_m
Joined: 2010-11-11,
User offline. Last seen 35 weeks 2 days ago.
Re: Text version of Scala Language Specification

How is the SLS PDF currently generated?

If it's written in LaTeX or something and the rendered to PDF it may be
easier to go directly from that format to a (more) readable plain text
version. In fact, it'd be nice to get the underlying source in git
somewhere.

Or is it being generated via one of those "Print to PDF" adaptors from
within (shudder) Microsoft Word? Or being composed in something like
Acrobat directly?

Maxime Lévesque
Joined: 2009-08-18,
User offline. Last seen 42 years 45 weeks ago.
Re: Re: Text version of Scala Language Specification

+1 for posting it on docs.scala-lang.org


2011/12/21 Simon Ochsenreither <simon [dot] ochsenreither [at] googlemail [dot] com>
Thanks!

Is it possible to put this into docs.scala-lang.org?

I wouldn't mind keeping it up to date as long as I don't have to chase the changes ...

Bye

extempore
Joined: 2008-12-17,
User offline. Last seen 35 weeks 3 days ago.
Re: Text version of Scala Language Specification


On Wed, Dec 21, 2011 at 11:00 AM, Donald McLean <dmclean62 [at] gmail [dot] com> wrote:
Calibre is your friend.

http://calibre-ebook.com/

So are you, now! I knew it couldn't be this hard.
The whitespace is still hopelessly mangled (which is particularly grating when the section is oh I don't know random example "the specification on whitespace") and there's lots and lots of this:

CompoundType
::=
AnnotType {‘with’ AnnotType} [Refinement]
|
Refinement
AnnotType
::=
SimpleType {Annotation}
SimpleType
::=
SimpleType TypeArgs
|
SimpleType ‘#’ id
|
StableId
|
Path ‘.’ ‘type’
|
‘(’ Types ’)’

Even so, it's a big improvement if only because it might make a completely automated translation possible.  I think I can manage to coalesce the whitespace.
Dr. Poigné Axel
Joined: 2011-11-09,
User offline. Last seen 42 years 45 weeks ago.
Re: Text version of Scala Language Specification

Hi Paul

An alternative is to use Wondershare's PDF converter on a Mac (at a
cost. However it's more or less one-click only with no hassle). I
tried it on the nightly build pdf. Best option is to translate to Word
and then save to a .txt or .rtf version (if you insist on it). For
Word and .rtf the layout is almost perfect, the .txt version is ok as
well but less readable. Cut and paste works well for all version if
you paste into Eclipse (I use the formatter anyway). Direct
translation of the Converter to .txt or .rtf gives less convincing
results.

- Axel

Jeff Olson
Joined: 2011-06-29,
User offline. Last seen 42 years 45 weeks ago.
Re: Text version of Scala Language Specification
tid: 8 status: 1 @Erik: I believe the source is in LaTeX:

http://lampsvn.epfl.ch/svn-repos/scala/scala-documentation/trunk/src/reference/ScalaReference.tex

(it would be nice if they moved this repo to git as well)

@Paul: have you tried any of the LaTeX to ascii converters listed here:

http://www.tex.ac.uk/cgi-bin/texfaq2html?label=fmtconv+toascii


-Jeff
geoff
Joined: 2008-08-20,
User offline. Last seen 1 year 25 weeks ago.
Re: Text version of Scala Language Specification

On Wed, Dec 21, 2011 at 08:00:27PM +0100, √iktor Ҡlang said
> Completely recommend going the same route as Akka with compiled sample code
> pulled into reST documents.

Yeah, I think the SLS would do very well as a sphinx document. I might
even take a stab at transcribing it.

ichoran
Joined: 2009-08-14,
User offline. Last seen 2 years 3 weeks ago.
Re: Text version of Scala Language Specification

On Thu, Dec 22, 2011 at 2:07 PM, Geoff Reedy <geoff [at] programmer-monk [dot] net> wrote:
On Wed, Dec 21, 2011 at 08:00:27PM +0100, √iktor Ҡlang said
> Completely recommend going the same route as Akka with compiled sample code
> pulled into reST documents.

Yeah, I think the SLS would do very well as a sphinx document. I might
even take a stab at transcribing it.

Wait, what?  It's already in a high-powered document markup language which has many converters available, and the proposal is to put it into a less powerful and extensible markup language so that...???

If it were in Word, okay, sure--but if it's actually already in LaTeX, what does reST buy you?

  --Rex

d_m
Joined: 2010-11-11,
User offline. Last seen 35 weeks 2 days ago.
Re: Text version of Scala Language Specification

On Thu, Dec 22, 2011 at 03:31:44PM -0500, Rex Kerr wrote:
> Wait, what? It's already in a high-powered document markup language which
> has many converters available, and the proposal is to put it into a less
> powerful and extensible markup language so that...???

incredulity +1

d_m
Joined: 2010-11-11,
User offline. Last seen 35 weeks 2 days ago.
Re: Text version of Scala Language Specification

I just got some nice results:

http://plastic-idolatry.com/scala-sls.txt

(Make sure your browser views this as UTF-8... if it uses Latin-1 there
will be weirdness.)

To create this I used the following recipe:

0. find/checkout svn repo, copy deps around and strip out font info from latex
1. htlatex ScalaReference.tex
2. elinks -dump -no-numbering -no-references ScalaReference.html > scala.txt

Step 0 was the most annoying because the SLS isn't in Git so I had to
hunt down the right SVN repo. Then I had to copy a bunch of the sty and
tex files around to be able to just invoke latex.

Step 1 was easy once I installed htlatex: http://tug.org/applications/tex4ht/mn.html

Step 2 was easy too.

I think the results are pretty nice, and the process should be
relatively repeatable provided an ant/make task to run the steps, and
provided you can figure out how to install the right fonts.

extempore
Joined: 2008-12-17,
User offline. Last seen 35 weeks 3 days ago.
Re: Text version of Scala Language Specification


On Thu, Dec 22, 2011 at 2:10 PM, Erik Osheim <erik [at] plastic-idolatry [dot] com> wrote:
I just got some nice results:

 http://plastic-idolatry.com/scala-sls.txt

Oh my you are my hero.
 0. find/checkout svn repo, copy deps around and strip out font info from latex
 1. htlatex ScalaReference.tex
 2. elinks -dump -no-numbering -no-references ScalaReference.html > scala.txt

You don't know how much time I've squandered on those early steps.  My difficulty was partly that I have zero background in latex, and also that I'm on OSX and all the tex tools seem to skew toward linux.  So I'm not too surprised I never came up with that, but man I'm glad you did.
d_m
Joined: 2010-11-11,
User offline. Last seen 35 weeks 2 days ago.
Re: Text version of Scala Language Specification

On Thu, Dec 22, 2011 at 05:22:57PM -0800, Paul Phillips wrote:
> Oh my you are my hero.

> You don't know how much time I've squandered on those early steps. My
> difficulty was partly that I have zero background in latex, and also that
> I'm on OSX and all the tex tools seem to skew toward linux. So I'm not too
> surprised I never came up with that, but man I'm glad you did.

Glad I could help!

I can try to update this periodically if someone at Typesafe or EPFL
can't bake these steps into ant (which would probably be easier, or at
least easier for me).

I don't suppose this lends any weight to my radical, bomb-throwing
numeric proposals does it? :)

extempore
Joined: 2008-12-17,
User offline. Last seen 35 weeks 3 days ago.
Re: Text version of Scala Language Specification


On Thu, Dec 22, 2011 at 6:15 PM, Erik Osheim <erik [at] plastic-idolatry [dot] com> wrote:
I don't suppose this lends any weight to my radical, bomb-throwing
numeric proposals does it? :)

If only I had weight to offer.  The one thing which looks sure in this domain is that there are irreconcilable opinions about how to do complicated things.  That is a difficult situation for the generalist who can't afford to get bogged down in debates about euclidean rings.  I think you might have better results narrowing the focus to the minimum which would allow for appealing external libraries.
dcsobral
Joined: 2009-04-23,
User offline. Last seen 38 weeks 5 days ago.
Re: Text version of Scala Language Specification

Say, could you get the HTML version on docs.scala-lang.org? You can
fork https://github.com/scala/scala.github.com, put it in there
somewhere (there's even a menu entry for it already, just waiting for
a suitable document!), and send a pull request.

On Fri, Dec 23, 2011 at 00:15, Erik Osheim wrote:
> On Thu, Dec 22, 2011 at 05:22:57PM -0800, Paul Phillips wrote:
>> Oh my you are my hero.
>
>> You don't know how much time I've squandered on those early steps.  My
>> difficulty was partly that I have zero background in latex, and also that
>> I'm on OSX and all the tex tools seem to skew toward linux.  So I'm not too
>> surprised I never came up with that, but man I'm glad you did.
>
> Glad I could help!
>
> I can try to update this periodically if someone at Typesafe or EPFL
> can't bake these steps into ant (which would probably be easier, or at
> least easier for me).
>
> I don't suppose this lends any weight to my radical, bomb-throwing
> numeric proposals does it? :)
>

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland