scala3 Documentation

The Scala 3 compiler, also known as Dotty.

6,323 stars Scala Scala 59 files · ~126,090 tokens #compiler#dotty#epfl#scala#scala3
RAW Doc

Technical Documentation: scala/scala3

ℹ️ Provenance: Multi-Tier Ingestion · CodeWiki Reference

Overview (`README.md`)

Scala 3


This is the home of the Scala 3 standard library, compiler, and language spec.
More documentation here.

Building a Local Distribution

  1. sbt dist/Universal/packageBin
  2. Find the newly-built distributions in dist/target/

Code of Conduct

Scala 3 uses the Scala Code of Conduct
for all communication and discussion. This includes both GitHub, Discord and
other more direct lines of communication such as email.

How to Contribute

License

Scala 3 is licensed under the Apache License Version 2.0


Overview (`bench/README.md`)

Scala 3 Compilation Benchmarks

Compilation benchmarks moved to a separate repository: lampepfl/scala3-benchmarks.


Overview (`community-build/README.md`)

Scala 3 Community Build

For information on the community build check out the Community Build section of
the Contributing
Docs
.


Overview (`directives-parser/README.md`)

Using Directives Parser

The scala3-directives-parser module parses //> using directives from source files.
It is shared between the Scala 3 compiler (REPL, test harness) and
Scala CLI.

The public entry point is UsingDirectivesParser.parse(IndexedSeq[Char]): UsingDirectivesResult.

Pipeline

Parsing proceeds in three phases:

mermaid
flowchart LR
  source["Source file"] --> extract["CommentExtractor"]
  extract --> lex["Lexer"]
  lex --> parse["Parser"]
  parse --> result["UsingDirectivesResult"]
  1. CommentExtractor scans the source and collects //> using lines from the
    directive region at the top of the file.
  2. Lexer tokenizes each directive line into a stream of tokens.
  3. Parser converts the token stream into UsingDirective nodes and diagnostics.

Directive region

Directives must appear in a preamble at the top of the file, before the first
line of code. The result includes a codeOffset field: the byte offset in the
original file where code begins.

Allowed before code

  • Blank lines
  • A #! shebang on the very first line only
  • Line comments (// ..., but not //> using ...)
  • Block comments (/* ... */), including multi-line and nested comments
  • Leading whitespace (spaces or tabs) before //> using
  • A UTF-8 BOM (\uFEFF) at the start of the file (stripped before parsing)

Not allowed / ignored

  • Directives inside block comments, line comments, or ScalaDoc comments
  • Directives after the first line of code (ignored with a warning)
  • A package declaration or any other code before directives (treats the file as
    having no directive region; post-code directives warn)
  • //> using on the same line after a block comment closes (/* comment */ //> using ...)
  • Inline block comments within a directive line (not supported; /* becomes part of the key)

Prefix requirement

The prefix //> using is required, with zero or more whitespace characters after >:

  • //> using scala 3 — valid
  • //>using scala 3 — valid
  • //> using scala 3 — valid
  • //> using scala 3 (with a tab) — valid
  • //> notUsing foo — treated as code

Grammar

text
Directives ::= { Directive }
Directive  ::= "using" Key Values
Key        ::= Ident                  (dotted keys are a single Ident, e.g. "test.dep")
Values     ::= { [Comma] Value }
Value      ::= StringLit | BoolLit | Ident

When no values follow the key, a single EmptyVal is produced (equivalent to a
flag with no argument).

Each directive occupies one line. Multiple directives are written on consecutive
lines:

scala
//> using scala 3
//> using dep com.lihaoyi::os-lib:0.11.4

Lexical rules

The lexer operates on the content of a single directive line (including the
//> prefix). Positions in tokens are relative to the original source file.

Bare identifiers and values

A bare token is a maximal run of non-whitespace characters. It stops before:

  • Whitespace
  • A comma followed by whitespace or end-of-line (see comma rule below)
  • A double quote " (whitespace is required before a quote; see errors below)

Bare tokens that are exactly using, true, or false are recognized as
special tokens. All other bare tokens become Ident values.

Values may contain ., :, =, and embedded commas (with no following
whitespace). Dotted keys like test.dep are stored as a single key string; the
lexer does not split dots in value position.

Double-quoted strings

Double-quoted strings support these escape sequences:

Escape Meaning
\n newline
\t tab
\r carriage return
\\ backslash
\" double quote
\uXXXX Unicode code point (4 hex digits)

An unterminated string produces a lexer error.

Backtick-quoted identifiers

Backtick-quoted text (`native-gc`) is treated as a bare Ident with the
backticks stripped. Empty backtick identifiers ( ``) produce a lexer error.

Boolean literals

The bare tokens true and false (case-sensitive) are parsed as boolean values
when they appear in value position.

Commas separating values (deprecated)

A comma is a value separator only when immediately followed by whitespace or
end-of-line:

  • a, b — two values (a and b); comma separator is deprecated and emits a warning
  • a,b — one value (a,b)
  • a ,b — two values (a and ,b); no comma separator
  • --enable-url-protocols=http,https — one value (embedded comma)
  • tabby:tabby:0.2.3,url=https://example.com/tabby.jar — one value (Coursier syntax)

Commas as separators are deprecated. Use whitespace separation instead.

Additional comma edge cases:

  • A lone , as a value is accepted literally
  • A trailing comma (a, b,) produces two values and two deprecation warnings
  • A double comma (a,, b) produces values a, and b, with warnings about
    the value ending in a comma and about comma separators

Value model

Each parsed value is a DirectiveValue:

Variant Description
StringVal(value, isQuoted, position) A string, either quoted or bare
BoolVal(value, position) Boolean true or false
EmptyVal(position) No value provided after the key

Two accessors reconstruct the text:

  • stringValue — content without surrounding quotes
  • rawText — source form ("hello" for quoted strings, bare text otherwise)

Diagnostics

Diagnostics are returned as UsingDirectiveDiagnostic(message, severity, position).

Severity When
Error Parse failure: missing key, unexpected token, lexer error
Warning Deprecated comma separator; directive after code; invalid //> prefix

Positions are 0-based (line, column, offset in the original file).

On parse errors the parser skips to the next line and continues.

Examples

Accepted

scala
//> using scala 3
//> using dep com.lihaoyi::os-lib:0.11.8
//> using dep com.lihaoyi::os-lib:0.11.8 com.lihaoyi::upickle:4.4.3
//> using test.dep munit::munit:1.3.3
//> using scalacOption "-Xfatal-warnings"
//> using publish.doc true
//> using toolkit
//> using dep tabby:tabby:0.2.3,url=https://example.com/tabby.jar
//> using dep com.lihaoyi::os-lib:0.11.8,exclude=com.lihaoyi%%geny
//> using packaging.graalvmArgs --enable-url-protocols=http,https
//> using `native-gc`

Warnings (still parsed where noted)

scala
//> using dep a, b                  // deprecated comma separator; both values parsed
//> using dep a,, b                 // value "a," ends with comma; comma separator
val x = 1
//> using scala 3                   // ignored: directive after code
scala
package x
//> using scala 3                   // ignored: code (package) before directive

Errors

scala
//> using                           // missing key after `using`
//> using using foo                 // `using` cannot be a key
//> using true foo                  // boolean literal cannot be a key
//> using dep "unterminated         // unterminated string literal

Overview (`pkgs/README.md`)

Configuration for Chocolatey

Official support for Chocolatey started by the release of Scala 3.6.0

[!IMPORTANT]
This folder contains the templates to generate the configuration for Chocolatey.
The scala.nuspec and chocolateyInstall.ps1 files needs to be rewritten by changing the following placeholders:

  • @LAUNCHER_VERSION@ : Placeholder for the current scala version to deploy
  • @LAUNCHER_URL@ : Placeholder for the URL to the windows zip released on GitHub
  • @LAUNCHER_SHA256@ : Placeholder for the SHA256 of the msi file released on GitHub

Important information


Overview (`scaladoc/README.md`)

Scaladoc

You can find the documentation to help better understand and contribute to
scaladoc here in the contributing guide.


Overview (`docs/_spec/README.md`)

WIP Scala 3 Language Specification

This is still a work in progress. There are still Scala 3 features missing, as well as some areas that have not been updated since 2.13 yet.

First of all, the language specification is meant to be correct, precise and clear.

Second, editing, previewing and generating output for the markdown should be simple and easy.

Third, we'd like to support different output formats. An html page per chapter with MathJax seems like a good start, as it satisfies the second requirement, and enables the first one.

Editing

We are using Jekyll to generate the html.

Check Gemfile for the current versions.

We aim to track the configuration GitHub Pages uses but differences may arise as GitHub Pages evolves.

Building

To preview locally, run the following commands in the docs/_spec subfolder:

text
env UID="$(id -u)" GID="$(id -g)" docker-compose up

and open http://localhost:4000/files/archive/spec/3.4/ to view the spec. Jekyll will rebuild as you edit the markdown, but make sure to restart it when you change _config.yml.

General Advice for editors

  • All files must be saved as UTF-8: ensure your editors are configured appropriately.

  • Use of the appropriate unicode characters instead of the latex modifiers for accents, etc. is necessary. For example, é instead of \'e.

  • MathJAX errors will appear within the rendered DOM as span elements with class mtext and style attribute color: red applied. It is possible to search for this combination in the development tools of the browser of your choice. In chrome, CTRL+F / CMD+F within the inspect element panel allows you to do this.

  • This document follows the "one sentence <=> one line" convention, with the following exceptions below.

    • A multiline code block is part of the sentence
    • An enumeration of links is long enough
  • Whenever doing an enumeration of the kind "a, ..., z", follow the following conventions:

    • It should always be "separator whitespace period period period separator whitespace", for example , ..., or ,\n...,\n for multiline.
    • If in a code block, only the elements (a and z above) should be in math mode (between forward ticks)
    • If in a math expression, the whole thing should be in a single math mode
    • Look at the Tuple Types section for an example of the different cases above.
  • Try to use "Note" blocks to point out logical conclusions that are not obvious, for examples, look at the Tuple Types section.

Macro replacements:

  • While MathJAX just support LaTeX style command definition, it is recommended to not use this as it will likely cause issues with preparing the document for PDF or ebook distribution.
  • \SS (which I could not find defined within the latex source) seems to be closest to \mathscr{S}
  • \TYPE is equivalent to `\boldsymbol{type}'
  • As MathJAX has no support for slanted font (latex command \sl), so in all instances this should be replaced with \mathit{}
  • The macro \U{ABCD} used for unicode character references can be replaced with \uABCD.
  • The macro \URange{ABCD}{DCBA} used for unicode character ranges can be replaced with \uABCD-\uDBCA.
  • The macro \commadots can be replaced with , … , (But should not, see above).
  • There is no adequate replacement for \textsc{...} (small caps) in pandoc markdown. While unicode contains a number of small capital letters, it is notably missing Q and X as these glyphs are intended for phonetic spelling, therefore these cannot be reliably used. For now, the best option is to use underscore emphasis and capitalise the text manually, _LIKE THIS_.

Unicode Character replacements

  • The unicode left and right single quotation marks (‘ and ’ (U+2018 and U+2019, respectively)) have been used in place of ` and ', where the quotation marks are intended to be paired. These can be typed on a mac using Option+] for a left quote and Option+Shift+] for the right quote.
  • Similarly for left and right double quotation marks (“ and ” (U+201C and U+201D, respectively)) in place of ". These can be typed on a mac using Option+[ and Option+Shift+].

Overview (`pkgs/chocolatey/README.md`)

Configuration for Chocolatey

Official support for Chocolatey started by the release of Scala 3.6.0

[!IMPORTANT]
This folder contains the templates to generate the configuration for Chocolatey.
The scala.nuspec and chocolateyInstall.ps1 files needs to be rewritten by changing the following placeholders:

  • @LAUNCHER_VERSION@ : Placeholder for the current scala version to deploy
  • @LAUNCHER_URL@ : Placeholder for the URL to the windows zip released on GitHub
  • @LAUNCHER_SHA256@ : Placeholder for the SHA256 of the msi file released on GitHub

Overview (`pkgs/msi/README.md`)

Important information

  • We can only build msi packages with stable version number (no RCs, nor Nightlies).
    Example of the error message when building with an RC
text
error CNDL0108 : The Product/@Version attribute's value, '3.5.1-RC1', is not a valid version.  Legal version values should look like 'x.x.x.x' where x is an integer from 0 to 65534

Overview (`tests/cmdTest-sbt-tests/README.md`)

Readme

Do not use this directory for testing sbt projects in general, add a test case to dotty/sbt-test

This directory is for sbt tests that can not be reproduced with sbt scripted tests.

Adding a test here will reduce the performance of running all tests.


Overview (`repl/src/fansi/README.md`)

Vendored from lihaoyi/fansi commit c8d4e5b56c46f2b360a441ca6d35620819a1ee52

Changes:

  • Added package dotty.vendored
  • private[this] -> private
  • protected[this] -> protected
  • :_* -> *
  • added using where necessary for implicit parameters
  • added an unsafe cast for null since the original builds without explicit nulls

Overview (`repl/src/pprint/README.md`)

Vendored from lihaoyi/pprint commit 66733cc563c1a4c8d694b3daba69ab643a50dd79

Changes:

  • Added package dotty.vendored
  • [_] -> [?]
  • private[this] -> private
  • :_* -> *
  • added using where necessary for implicit parameters
  • added an unsafe cast for null since the original builds without explicit nulls
  • added a cast to String | Null for toString since the original builds without explicit nulls
  • Commented out an unreachable match case in TPrintImpl (line 116)
  • Added a REPL hook to honor user-defined Product.toString implementations

Overview (`repl/src/sourcecode/README.md`)

Vendored from lihaoyi/sourcecode commit 7e738aa077e6634fc5346df5f6ccbac52be861ec

Changes:

  • Added package dotty.vendored
  • [_] -> [?]

Overview (`tests/explicit-nulls/unsafe-common/README.md`)

Common tests for unsafe-nulls feature.

All the tests should be compiled with -language:unsafeNulls.

All the tests should produce errors at // error comment locations without -language:unsafeNulls.


Overview (`tests/neg-custom-args/i20491/README.md`)

Test case for https://github.com/scala/scala3/issues/20491

Test setup

The test simulates a missing class dependency:

  • cp/testpkg/A.class + cp/testpkg/A.tasty - A Scala trait that references otherpkg.MissingDep
  • cp/otherpkg/ - An empty directory (MissingDep.class is missing)

How to regenerate the test files

otherpkg/MissingDep.java

java
package otherpkg;
public class MissingDep {}

A.scala

scala
package testpkg
trait A:
  def getDep: otherpkg.MissingDep
bash
scala-cli compile A.scala otherpkg/MissingDep.java -d out

Copy A.class and A.tasty to cp/testpkg/, and ensure cp/otherpkg/ directory
exists but is empty (do not include MissingDep.class).


Overview (`tests/neg-custom-args/missing-java-outer-dependency/README.md`)

Missing Java outer class dependency tests

Regenerate the test files

broken/Outer.java

java
package broken;
public class Outer {
  public static class Inner {}
}

broken/Child.java

java
package broken;
public class Child extends Outer.Inner {}
bash
javac -d out broken/Outer.java broken/Child.java

Copy Child.class and Outer$Inner.class to cp/broken/, but do not copy
Outer.class.

suggestions/SearchRoot.java

java
package suggestions;

public class SearchRoot extends broken.Child {}
bash
javac -classpath out -d search-root-out suggestions/SearchRoot.java

Copy SearchRoot.class to cp/suggestions/.


Overview (`bench-micro/src/main/scala/dotty/tools/benchmarks/specializedtraits/README.md`)

Specialized Trait Benchmarks

Run

  1. Publish the compiler first and check that the version in the benchmark file corresponds to the generated version,
  2. Kill bloop server if republishing an existing version:
    scala-cli --power bloop exit
  3. Run the benchmark with:
text
scala-cli --power --jmh bench-micro/src/main/scala/dotty/tools/benchmarks/specializedtraits/VectorDotProduct.scala

Troubleshooting

  • May have to run it again / delete .scala-build and rerun if you get a class not found error from scala-cli first time - the --jmh flag is still experimental.

.Ai INDEX (`docs/.ai/INDEX.md`)

AI Contributor Guide

This directory is the canonical, tool-agnostic source for project-specific AI workflows in this repository.

Workflows


Docs Index (`docs/_docs/index.md`)


layout: index redirectFrom: /docs/index.html

This website contains the developer documentation of the Scala 3 compiler. It targets developers interested in contributing to the compiler, or learning its internals. If you want to learn how to use Scala, go here.


Spec Index (`docs/_spec/index.md`)


title: Scala Language Specification layout: toc

{% include table-of-contents.yml %}

Authors and Contributors

Martin Odersky, Philippe Altherr, Vincent Cremet, Sébastien Doeraene, Gilles Dubochet, Burak Emir, Philipp Haller, Stéphane Micheloud, Nikolay Mihaylov, Adriaan Moors, Lukas Rytz, Michel Schinz, Erik Stenman, Matthias Zenger

Markdown Conversion by Iain McGinniss.

Disclaimer: Work in Progress

This specification for Scala 3 is still a work in progress.
Some features added in Scala 3 are missing.
Here is a list of the most important missing aspects:

  • extension methods
  • given and using contextual abstractions
  • type-class derivation with derives
  • behavior of structural types based on Selectable
  • meta-programming with inline defs and quotes
  • match types (pending a Scala Improvement Proposal with a full specification)

For those features, the best reference so far remains the Scala 3 Reference.

Preface

Scala is a Java-like programming language which unifies
object-oriented and functional programming. It is a pure
object-oriented language in the sense that every value is an
object. Types and behavior of objects are described by
classes. Classes can be composed using mixin composition. Scala is
designed to work seamlessly with less pure but mainstream
object-oriented languages like Java.

Scala is a functional language in the sense that every function is a
value. Nesting of function definitions and higher-order functions are
naturally supported. Scala also supports a general notion of pattern
matching which can model the algebraic types used in many functional
languages.

Scala has been designed to interoperate seamlessly with Java.
Scala classes can call Java methods, create Java objects, inherit from Java
classes and implement Java interfaces. None of this requires interface
definitions or glue code.

Scala has been developed from 2001 in the programming methods laboratory at EPFL.
Version 1.0 was released in November 2003.
This document describes the third version of the language, which was released in May 2021.
It acts as a reference for the language definition and some core library modules.
It is not intended to teach Scala or its concepts; for this there are other documents.

Scala has been a collective effort of many people. The design and the
implementation of version 1.0 was completed by Philippe Altherr,
Vincent Cremet, Gilles Dubochet, Burak Emir, Stéphane Micheloud,
Nikolay Mihaylov, Michel Schinz, Erik Stenman, Matthias Zenger, and
the author. Iulian Dragos, Gilles Dubochet, Philipp Haller, Sean
McDirmid, Lex Spoon, and Geoffrey Washburn joined in the effort to
develop the second version of the language and tools. Gilad Bracha,
Craig Chambers, Erik Ernst, Matthias Felleisen, Shriram Krishnamurti,
Gary Leavens, Sebastian Maneth, Erik Meijer, Klaus Ostermann, Didier
Rémy, Mads Torgersen, and Philip Wadler have shaped the design of
the language through lively and inspiring discussions and comments on
previous versions of this document. The contributors to the Scala
mailing list have also given very useful feedback that helped us
improve the language and its tools.


Docs Contributing Getting Started (`docs/_docs/contributing/getting-started.md`)


layout: doc-page title: Getting Started redirectFrom: /docs/contributing/workflow.html

Scala CLA

Sometime before submitting your pull request you'll want to make sure you have
signed the Scala CLA. You can read more about why we require a CLA
and what exactly is included in it here.

Making sure the team is aware

Before digging into an issue or starting on a new feature it's a good idea to
make sure an issue or a discussion has been
created outlining what you plan to work on. This is both for your and the team's
benefit. It ensures you get the help you need, and also gives the compiler team
a heads-up that someone is working on an issue.

For some small changes like documentation, this isn't always necessary, but it's
never a bad idea to check.

Requirements

  • git is essential for managing the Scala 3 code, and contributing to GitHub,
    where the code is hosted.
  • A Java Virtual Machine (JDK 8 or higher), required for running the build tool. Do note, however, that the continuous integration test suite is run on JDK 17.
  • sbt, the build tool required to build the Scala 3 compiler and libraries.

Nice To Have

An IDE, such as Metals will help you develop in Scala 3 with features such as
autocompletion, code navigation, debugging, and interactive worksheets.

Another popular options is IntelliJ IDEA for
Scala
.

Compiling and Running

Start by cloning the repository:

bash
$ git clone https://github.com/scala/scala3.git
$ cd scala3

Dotty provides a standard sbt build: compiling, running and starting a repl can
all be done from within sbt:

bash
$ sbt
> scalac tests/pos/HelloWorld.scala
> scala HelloWorld
hello world

There are also bash scripts that can be used in the same way. Assuming that you
have cloned the Dotty repo locally, append the following line on your
.bash_profile, or equivalent for your shell:

shell
$ export PATH=<path to cloned dotty>/bin:$PATH

and you will be able to run the corresponding commands directly from your console:

shell
# Compile code using Dotty
$ scalac tests/pos/HelloWorld.scala

# Run it with the proper classpath
$ scala HelloWorld

Note that the scalac and scala scripts have slow roundtrip times when working on the compiler codebase: whenever
any source file changes they invoke sbt dist/pack first.

As an alternative, run the buildQuick task in sbt. It builds the compiler and writes its classpath to the bin/.cp
file, which enables the scalacQ and scalaQ scripts in the bin/ folder.

Starting a REPL

bash
$ sbt
> repl
Welcome to Scala.next (pre-alpha)  (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_101).
Type in expressions to have them evaluated.
Type :help for more information.
scala>

or via bash:

bash
$ scala

Publish to local repository

To test our cloned compiler on local projects:

bash
$ sbt publishLocal

Then in the build.sbt file of a test project:

bash
ThisBuild / scalaVersion := "<dotty-version>-bin-SNAPSHOT"

where dotty-version can be found in the file project/Build.scala, like 3.0.0-M2

Generating Documentation

To generate this page and other static page docs, run

bash
$ sbt
> scaladoc/generateScalaDocumentation

For more information, see the scaladoc section.

Community

The main development discussion channels are:


Docs Contributing Index (`docs/_docs/contributing/index.md`)


layout: index title: Contributing

This guide is intended to give new contributors the knowledge they need to
become productive and fix issues or implement new features in Scala 3. It
also documents the inner workings of the Scala 3 compiler, dotc.

This is a living document

Keep in mind that the code for dotc is continually changing, so the ideas
discussed in this guide may fall out of date. This is a living document, so
please consider contributing to it on
GitHub if
you notice anything out of date, or report any issues
here.

Get the most from This Guide

dotc is built with Scala 3, fully utilising its new
features
. It is
recommended that you first have some familiarity with Scala 3 to get the most
out of this guide. You can learn more in the language
reference
.

Many code snippets in this guide make use of shell commands (a line beginning
with $), and in this case a bash compatible shell is assumed. You may have
to look up how to translate commands to your shell.

What is a Compiler?

Let's start at the beginning and first look at the question of "what is a
compiler?". A compiler is a program that takes as input text, representing a
program in one language and produces as output the same program, written in
another programming language.

The Scala Compiler

As an example, dotc takes text input, verifies that it is a valid Scala program
and then produces as output the same program, but written in Java bytecode, and optionally
in SJSIR when producing Scala.js output.


Docs Reference Overview (`docs/_docs/reference/overview.md`)


layout: doc-page title: "Reference" nightlyOf: https://docs.scala-lang.org/scala3/reference/overview.html redirectFrom: overview.html

Scala 3 implements many language changes and improvements over Scala 2.
In this reference, we discuss design decisions and present important differences compared to Scala 2.

Goals

The language redesign was guided by three main goals:

  • Strengthen Scala's foundations.
    Make the full programming language compatible with the foundational work on the
    DOT calculus
    and apply the lessons learned from that work.
  • Make Scala easier and safer to use.
    Tame powerful constructs such as implicits to provide a gentler learning curve. Remove warts and puzzlers.
  • Further improve the consistency and expressiveness of Scala's language constructs.

Corresponding to these goals, the language changes fall into seven categories:
(1) Core constructs to strengthen foundations, (2) simplifications and (3) restrictions, to make the language easier and safer to use, (4) dropped constructs to make the language smaller and more regular, (5) changed constructs to remove warts, and increase consistency and usability, (6) new constructs to fill gaps and increase expressiveness, (7) a new, principled approach to metaprogramming that replaces Scala 2 experimental macros.

Essential Foundations

These new constructs directly model core features of DOT, higher-kinded types, and the SI calculus for implicit resolution.

Simplifications

These constructs replace existing constructs with the aim of making the language safer and simpler to use, and to promote uniformity in code style.

  • Trait parameters
    replace early initializers with a more generally useful construct.
  • Given instances
    replace implicit objects and defs, focussing on intent over mechanism.
  • Using clauses
    replace implicit parameters, avoiding their ambiguities.
  • Extension methods
    replace implicit classes with a clearer and simpler mechanism.
  • Opaque type aliases
    replace most uses of value classes while guaranteeing the absence of boxing.
  • Top-level definitions
    replace package objects, dropping syntactic boilerplate.
  • Export clauses
    provide a simple and general way to express aggregation, which can replace
    the previous facade pattern of package objects inheriting from classes.
  • Vararg splices
    now use the form xs* in function arguments and patterns instead of xs: _* and xs @ _*,
  • Universal apply methods
    allow using simple function call syntax instead of new expressions. new expressions stay around
    as a fallback for the cases where creator applications cannot be used.

With the exception of early initializers and old-style vararg patterns, all superseded constructs continue to be available in Scala 3.0. The plan is to deprecate and phase them out later.

Value classes (superseded by opaque type aliases) are a special case. There are currently no deprecation plans for value classes, since we might bring them back in a more general form if they are supported natively by the JVM as is planned by project Valhalla.

Restrictions

These constructs are restricted to make the language safer.

  • Implicit Conversions:
    there is only one way to define implicit conversions instead of many, and potentially surprising implicit conversions require a language import.
  • Given Imports:
    implicits now require a special form of import, to make the import clearly visible.
  • Type Projection:
    only classes can be used as prefix C of a type projection C#A. Type projection on abstract types is no longer supported since it is unsound.
  • Multiversal Equality:
    implement an "opt-in" scheme to rule out nonsensical comparisons with == and !=.
  • infix:
    make method application syntax uniform across code bases.

Unrestricted implicit conversions continue to be available in Scala 3.0, but will be deprecated and removed later. Unrestricted versions of the other constructs in the list above are available only under -source 3.0-migration.

Dropped Constructs

These constructs are proposed to be dropped without a new construct replacing them. The motivation for dropping these constructs is to simplify the language and its implementation.

The date when these constructs are dropped varies. The current status is:

  • Not implemented at all:
    • DelayedInit, existential types, weak conformance.
  • Supported under -source 3.0-migration:
    • procedure syntax, class shadowing, symbol literals, auto application, auto tupling in a restricted form.
  • Supported in 3.0, to be deprecated and phased out later:

Changes

These constructs have undergone changes to make them more regular and useful.

  • Structural Types:
    They now allow pluggable implementations, which greatly increases their usefulness. Some usage patterns are restricted compared to the status quo.
  • Name-based pattern matching:
    The existing undocumented Scala 2 implementation has been codified in a slightly simplified form.
  • Automatic Eta expansion:
    Eta expansion is now performed universally also in the absence of an expected type. The postfix _ operator is thus made redundant. It will be deprecated and dropped after Scala 3.0.
  • Implicit Resolution:
    The implicit resolution rules have been cleaned up to make them more useful and less surprising. Implicit scope is restricted to no longer include package prefixes.

Most aspects of old-style implicit resolution are still available under -source 3.0-migration. The other changes in this list are applied unconditionally.

New Constructs

These are additions to the language that make it more powerful or pleasant to use.

  • Enums provide concise syntax for enumerations and algebraic data types.
  • Parameter untupling avoids having to use case for tupled parameter destructuring.
  • Dependent function types generalize dependent methods to dependent function values and types.
  • Polymorphic function types generalize polymorphic methods to polymorphic function values and types.
    Current status: There is a proposal and a merged prototype implementation, but the implementation has not been finalized (it is notably missing type inference support).
  • Kind polymorphism allows the definition of operators working equally on types and type constructors.
  • @targetName annotations make it easier to interoperate with code written in other languages and give more flexibility for avoiding name clashes.

Metaprogramming

The following constructs together aim to put metaprogramming in Scala on a new basis. So far, metaprogramming was achieved by a combination of macros and libraries such as Shapeless that were in turn based on some key macros. Current Scala 2 macro mechanisms are a thin veneer on top of the current Scala 2 compiler, which makes them fragile and in many cases impossible to port to Scala 3.

It's worth noting that macros were never included in the Scala 2 language specification and were so far made available only under an -experimental flag. This has not prevented their widespread usage.

To enable porting most uses of macros, we are experimenting with the advanced language constructs listed below. These designs are more provisional than the rest of the proposed language constructs for Scala 3.0. There might still be some changes until the final release. Stabilizing the feature set needed for metaprogramming is our first priority.

  • Match Types
    allow computation on types.
  • Inline
    provides by itself a straightforward implementation of some simple macros and is at the same time an essential building block for the implementation of complex macros.
  • Quotes and Splices
    provide a principled way to express macros and staging with a unified set of abstractions.
  • Type class derivation
    provides an in-language implementation of the Gen macro in Shapeless and other foundational libraries. The new implementation is more robust, efficient and easier to use than the macro.
  • By-name context parameters
    provide a more robust in-language implementation of the Lazy macro in Shapeless.

See Also

A classification of proposed language features is
an expanded version of this page that adds the status (i.e. relative importance to be a part of Scala 3, and relative urgency when to decide this) and expected migration cost
of each language construct.


Spec TODOreference Overview (`docs/_spec/TODOreference/overview.md`)


layout: doc-page title: "Reference" nightlyOf: https://docs.scala-lang.org/scala3/reference/overview.html redirectFrom: overview.html

Scala 3 implements many language changes and improvements over Scala 2.
In this reference, we discuss design decisions and present important differences compared to Scala 2.

Goals

The language redesign was guided by three main goals:

  • Strengthen Scala's foundations.
    Make the full programming language compatible with the foundational work on the
    DOT calculus
    and apply the lessons learned from that work.
  • Make Scala easier and safer to use.
    Tame powerful constructs such as implicits to provide a gentler learning curve. Remove warts and puzzlers.
  • Further improve the consistency and expressiveness of Scala's language constructs.

Corresponding to these goals, the language changes fall into seven categories:
(1) Core constructs to strengthen foundations, (2) simplifications and (3) restrictions, to make the language easier and safer to use, (4) dropped constructs to make the language smaller and more regular, (5) changed constructs to remove warts, and increase consistency and usability, (6) new constructs to fill gaps and increase expressiveness, (7) a new, principled approach to metaprogramming that replaces Scala 2 experimental macros.

Essential Foundations

These new constructs directly model core features of DOT, higher-kinded types, and the SI calculus for implicit resolution.

Simplifications

These constructs replace existing constructs with the aim of making the language safer and simpler to use, and to promote uniformity in code style.

  • Trait parameters
    replace early initializers with a more generally useful construct.
  • Given instances
    replace implicit objects and defs, focussing on intent over mechanism.
  • Using clauses
    replace implicit parameters, avoiding their ambiguities.
  • Extension methods
    replace implicit classes with a clearer and simpler mechanism.
  • Opaque type aliases
    replace most uses of value classes while guaranteeing the absence of boxing.
  • Top-level definitions
    replace package objects, dropping syntactic boilerplate.
  • Export clauses
    provide a simple and general way to express aggregation, which can replace
    the previous facade pattern of package objects inheriting from classes.
  • Vararg splices
    now use the form xs* in function arguments and patterns instead of xs: _* and xs @ _*,
  • Universal apply methods
    allow using simple function call syntax instead of new expressions. new expressions stay around
    as a fallback for the cases where creator applications cannot be used.

With the exception of early initializers and old-style vararg patterns, all superseded constructs continue to be available in Scala 3.0. The plan is to deprecate and phase them out later.

Value classes (superseded by opaque type aliases) are a special case. There are currently no deprecation plans for value classes, since we might bring them back in a more general form if they are supported natively by the JVM as is planned by project Valhalla.

Restrictions

These constructs are restricted to make the language safer.

  • Implicit Conversions:
    there is only one way to define implicit conversions instead of many, and potentially surprising implicit conversions require a language import.
  • Given Imports:
    implicits now require a special form of import, to make the import clearly visible.
  • Type Projection:
    only classes can be used as prefix C of a type projection C#A. Type projection on abstract types is no longer supported since it is unsound.
  • Multiversal Equality:
    implement an "opt-in" scheme to rule out nonsensical comparisons with == and !=.
  • infix:
    make method application syntax uniform across code bases.

Unrestricted implicit conversions continue to be available in Scala 3.0, but will be deprecated and removed later. Unrestricted versions of the other constructs in the list above are available only under -source 3.0-migration.

Dropped Constructs

These constructs are proposed to be dropped without a new construct replacing them. The motivation for dropping these constructs is to simplify the language and its implementation.

The date when these constructs are dropped varies. The current status is:

  • Not implemented at all:
    • DelayedInit, existential types, weak conformance.
  • Supported under -source 3.0-migration:
    • procedure syntax, class shadowing, symbol literals, auto application, auto tupling in a restricted form.
  • Supported in 3.0, to be deprecated and phased out later:

Changes

These constructs have undergone changes to make them more regular and useful.

  • Structural Types:
    They now allow pluggable implementations, which greatly increases their usefulness. Some usage patterns are restricted compared to the status quo.
  • Name-based pattern matching:
    The existing undocumented Scala 2 implementation has been codified in a slightly simplified form.
  • Automatic Eta expansion:
    Eta expansion is now performed universally also in the absence of an expected type. The postfix _ operator is thus made redundant. It will be deprecated and dropped after Scala 3.0.
  • Implicit Resolution:
    The implicit resolution rules have been cleaned up to make them more useful and less surprising. Implicit scope is restricted to no longer include package prefixes.

Most aspects of old-style implicit resolution are still available under -source 3.0-migration. The other changes in this list are applied unconditionally.

New Constructs

These are additions to the language that make it more powerful or pleasant to use.

  • Enums provide concise syntax for enumerations and algebraic data types.
  • Parameter untupling avoids having to use case for tupled parameter destructuring.
  • Dependent function types generalize dependent methods to dependent function values and types.
  • Polymorphic function types generalize polymorphic methods to polymorphic function values and types.
    Current status: There is a proposal and a merged prototype implementation, but the implementation has not been finalized (it is notably missing type inference support).
  • Kind polymorphism allows the definition of operators working equally on types and type constructors.
  • @targetName annotations make it easier to interoperate with code written in other languages and give more flexibility for avoiding name clashes.

Metaprogramming

The following constructs together aim to put metaprogramming in Scala on a new basis. So far, metaprogramming was achieved by a combination of macros and libraries such as Shapeless that were in turn based on some key macros. Current Scala 2 macro mechanisms are a thin veneer on top of the current Scala 2 compiler, which makes them fragile and in many cases impossible to port to Scala 3.

It's worth noting that macros were never included in the Scala 2 language specification and were so far made available only under an -experimental flag. This has not prevented their widespread usage.

To enable porting most uses of macros, we are experimenting with the advanced language constructs listed below. These designs are more provisional than the rest of the proposed language constructs for Scala 3.0. There might still be some changes until the final release. Stabilizing the feature set needed for metaprogramming is our first priority.

  • Match Types
    allow computation on types.
  • Inline
    provides by itself a straightforward implementation of some simple macros and is at the same time an essential building block for the implementation of complex macros.
  • Quotes and Splices
    provide a principled way to express macros and staging with a unified set of abstractions.
  • Type class derivation
    provides an in-language implementation of the Gen macro in Shapeless and other foundational libraries. The new implementation is more robust, efficient and easier to use than the macro.
  • By-name context parameters
    provide a more robust in-language implementation of the Lazy macro in Shapeless.

See Also

A classification of proposed language features is
an expanded version of this page that adds the status (i.e. relative importance to be a part of Scala 3, and relative urgency when to decide this) and expected migration cost
of each language construct.


Scaladoc Testcases Docs Docs Index (`scaladoc-testcases/docs/_docs/index.md`)



scala
val someVariable: Int = 2
scala sc:fail
trait RenderingContext
class Renderer(using RenderingContext)
val renderer: Renderer = Renderer()
scala
trait Ord:
    type Self

  trait SemiGroup:
    type Self
    extension (x: Self) def combine(y: Self): Self
scala sc:fail sc-opts:-werror:true
def exampleShouldError(input: Option[String]): Unit = 
  input match
    case Some("foo") => ???
scala sc:compile sc-opts:-werror:false
def exampleShouldWarn(input: Option[String]): Unit = 
  input match
    case Some("foo") => ???

Docs Contributing Architecture Index (`docs/_docs/contributing/architecture/index.md`)


layout: index title: High Level Architecture

This chapter of the guide describes the architecture and concepts of dotc,
the Scala 3 compiler, including answers to questions such as:

  • "What are the transformations that happen to my code?"
  • "How do I run a compiler programatically?"
  • "What are symbols, denotations, names and types?"
  • "What is a compiler phase?"
  • "What is the compiler Context?"

and many more.


Docs Contributing Procedures Index (`docs/_docs/contributing/procedures/index.md`)


layout: index title: Procedures

This chapter of the guide describes:


Docs Reference Enums Enums Index (`docs/_docs/reference/enums/enums-index.md`)


layout: index title: "Enums" movedTo: https://docs.scala-lang.org/scala3/reference/enums/index.html

This chapter documents enums in Scala 3.


Docs Reference Experimental Overview (`docs/_docs/reference/experimental/overview.md`)


layout: doc-page title: "Experimental" nightlyOf: https://docs.scala-lang.org/scala3/reference/experimental/overview.html redirectFrom: overview.html

Experimental language features

All experimental language features can be found under the scala.language.experimental package.
They are enabled by importing the feature or using the -language compiler flag.

Experimental language imports

In general, experimental language features can be imported in an experimental scope (see experimental definitions).
They can be imported at the top-level if all top-level definitions are @experimental.

`-experimental` compiler flag

This flag enables the use of any experimental language feature in the project.
It does this by adding an @experimental annotation to all top-level definitions.
Hence, dependent projects also have to be experimental.

Experimental language features supported by special compiler options

Some experimental language features that are still in research and development can be enabled with special compiler options. These include

  • -Yexplicit-nulls. Enable support for tracking null references in the type system.
  • -Ycc. Enable support for capture checking.

Docs Reference Preview Overview (`docs/_docs/reference/preview/overview.md`)


layout: doc-page title: "Preview" nightlyOf: https://docs.scala-lang.org/scala3/reference/preview/overview.html redirectFrom: overview.html

Preview language features

New Scala language features or standard library APIs are initially introduced as experimental, but once they become fully implemented and accepted by the SIP these can become a preview features.

Preview language features and APIs are guaranteed to be standardized in some next Scala minor release, but allow the compiler team to introduce small, possibly binary incompatible, changes based on the community feedback.
These can be used by early adopters who can accept the possibility of binary compatibility breakage. For instance, preview features could be used in some internal tool or application. On the other hand, preview features are discouraged in publicly available libraries.

More information about preview features can be found in preview definitions guide

`-preview` compiler flag

This flag enables the use of all preview language feature in the project.

List of available preview features


Spec APPLIEDreference Enums Enums Index (`docs/_spec/APPLIEDreference/enums/enums-index.md`)


layout: index title: "Enums" nightlyOf: https://docs.scala-lang.org/scala3/reference/enums/index.html

This chapter documents enums in Scala 3.


Spec TODOreference Experimental Overview (`docs/_spec/TODOreference/experimental/overview.md`)


layout: doc-page title: "Experimental" nightlyOf: https://docs.scala-lang.org/scala3/reference/experimental/overview.html redirectFrom: overview.html

Experimental language features

All experimental language features can be found under the scala.language.experimental package.
They are enabled by importing the feature or using the -language compiler flag.

Experimental language imports

In general, experimental language features can be imported in an experimental scope (see experimental definitions).
They can be imported at the top-level if all top-level definitions are @experimental.

Experimental language features supported by special compiler options

Some experimental language features that are still in research and development can be enabled with special compiler options. These include

  • -Yexplicit-nulls. Enable support for tracking null references in the type system.
  • -Ycc. Enable support for capture checking.

Docs Reference Experimental Capture Checking Overview (`docs/_docs/reference/experimental/capture-checking/overview.md`)


layout: doc-page title: "Tracked Capabilities Overview" nightlyOf: https://docs.scala-lang.org/scala3/reference/experimental/capture-checking/overview.html

Introduction

scala sc-hidden sc-name:overview-cc-context
import language.experimental.captureChecking
import caps.*
scala sc-hidden sc-name:overview-mut-context
import language.experimental.captureChecking
import caps.*

Tracked capabilities are the most important new feature of Scala. This page gives an overview of
the underlying concepts, focusing on what capabilities can express and what one can do with them.

For a more systematic description of all the details we refer you to the following pages:

Tracked capabilities are supported under Scala's capture checking extension, which can be enabled
by the language import

scala
import language.experimental.captureChecking

Some more features of capture checking having to do with mutable data structures and alias control currently require a separate language import

scala
import language.experimental.separationChecking

Both extensions are experimental, which means that details can still change. Capture checking is by now quite mature and we expect it to be stabilized soon. Separation checking is still a bit more fluid at present.

Capabilities

Informally, a capability is a value "of interest". For instance, a file handle, an access permission token, or a mutable data structure all make sense as capabilities. But the pair ("hello", "world!") is just a value, not a capability. Often capabilities are associated with effects. For instance, a file handle gives access to the effect of reading or writing it.

One can designate a value as a capability by making the type of the value extend directly or indirectly a standard trait Capability. For instance, a File can be declared to be a capability like this:

scala sc-name:overview-file-context sc-compile-with:overview-cc-context
class File(path: String) extends ExclusiveCapability
//{
extension (file: File)
  def close(): Unit = ()
  def println(message: String): Unit = ()
//}

Here, ExclusiveCapability is a subtrait of Capability that prevents concurrent accesses.

Capability Tracking

Capabilities in Scala 3 are tracked. This means that we record in a type which capabilities can be accessed by values of that type. We write A^{c} for the type of values of type A that can access the capability c.

For instance we can define a class Logger for sending log messages to a file and instantiate it like this:

scala sc-name:overview-logger-context sc-compile-with:overview-file-context
class Logger(file: File)
//{
extension (logger: Logger^)
  def log(message: String): Unit = ()
//}

val out: File^ = new File("~/some/bits")
val lg: Logger^{out} = new Logger(out)

Note the type Logger^{out} of lg above. It indicates not only that lg is of class Logger but also that it can access file out. We also say lg captures out and call Logger^{out} a capturing type.

Generally, the type A^{c₁, ..., cₙ} stands for instances that retain capabilities c₁, ..., cₙ.
If class A does not extend Capability, then the type A alone stands for instances
that retain no capabilities, i.e. A is equivalent to A^{}. We also say A is pure.
The opposite of pure A describes instances of A that can retain arbitrary capabilities.
This type is A^{any}, or, shorter, A^.

Values of capturing types are themselves considered capabilities. For instance lg above is treated as a capability even though its class Logger does not extend Capability.

Capability sets induce a subtyping relation, where smaller sets lead to smaller types.
Furthermore, if c is of a capturing type A^{c₁, ..., cₙ} then we also have {c} <: {c₁, ..., cₙ}.
We say in this case that c refines the underlying capture set {c₁, ..., cₙ}.

For instance, if out and lg are capabilities as defined above and f is some other capability, we have

text
A  <:  A^{lg}  <:  A^{out}  <:  A^{out, f}  <:  A^

Function Types

Function types can also be equipped with capability sets.
The function type A -> B is considered to be pure, so it cannot
retain any capability. We then use the following shorthands.

scala sc:nocompile
A ->{c₁, ..., cₙ} B   =  (A -> B)^{c₁, ..., cₙ}
                A => B   =  A ->{any} B

A function captures any capabilities accessed by its body. For instance the function

scala sc-compile-with:overview-logger-context
val next: Int ->{lg} Int = (x: Int) =>
  lg.log(s"called with parameter $x")
  x + 1

has type Int ->{lg} Int, which is a subtype of Int => Int.

Scala systematically distinguishes methods, which are members of classes and objects, from functions, which are objects themselves. Methods don't have expressible types and consequently don't have capability sets that can be tracked. Instead, the capability set is associated with the enclosing object. For instance, in

scala sc-compile-with:overview-logger-context
val exec: Runnable^{lg} = new Runnable:
  def run(): Unit = lg.log("called")

the value exec has type Runnable^{lg} since lg is accessed by Runnable's method run.
Methods can be converted to functions by just naming the method without passing any parameters (this is called eta expansion). For instance the value exec.run would have type () ->{lg} Unit.

Lifetimes

One consequence of tracking capabilities in types is that we can control their lifetimes.
For instance, here is a function that runs an operation op while providing a logger to a fresh
file. After the operation is finished, the file is closed and the result of the operation is returned.
The function is generic: the result type of the operation is the type parameter T, which can be instantiated as needed.

scala sc-name:overview-logged-context sc-compile-with:overview-logger-context
def logged[T](op: Logger^ => T): T =
  val f = new File("logfile")
  val l: Logger^{f} = new Logger(f)
  val result = op(l)
  f.close()
  result

A problematic use of the function would leak the logger l in the result of the operation. For instance like this:

scala sc:fail sc-compile-with:overview-logged-context
val bad = logged { l =>
  () => l.log("too late!")
}

Here, the result of the operation passed to logged is the nested function () => l.log("too late!"). This is also the value of bad. Hence, the call bad() would invoke l.log, but at this point the file underlying the logger was already closed by logged. Fortunately, the definition of bad is rejected in Scala 3's type system. Essentially, the type parameter T in the definition of logged must be independent of the identity of the logger passed to op. In the bad usage scenario, this requirement is violated since the result type of op has type () ->{l} Unit, so it does depend on the logger parameter in its capture set.

The fine grained control of lifetimes is one of the properties that set tracked capabilities apart from traditional untracked ones.

Implicit Capability Passing

Capabilities like out or lg are objects with which a program interacts as usual. This aspect of object capabilities is one of their strengths since it leads to ergonomic notation. Capabilities are also often used to establish some kind of context that establishes permissions to execute some effects.

For instance, in the Gears framework for concurrent systems we have Async capabilities that allow a computation to suspend while waiting for an external event (and possibly be cancelled in the process). This is modeled by having the Async class extend a capability trait:

scala sc-name:overview-async-context sc-compile-with:overview-file-context
class Async extends SharedCapability
class Data

// A suspendable method using an Async capability
def readDataEventually(file: File)(using async: Async): Data = new Data

One common issue with traditional capabilities is that passing many capabilities as parameters to all the places that need them can get tedious quickly. In Scala this is much less of a problem since capabilities can be passed as implicit parameters via using clauses. For instance, the following method calls readDataEventually without having to pass the parameter async explicitly.

scala sc-compile-with:overview-async-context
def processData(using Async): Data =
  val file = new File("~/some/path")
  readDataEventually(file)

Since the parameter is not mentioned, we also don't need a name for it in its definition. So the method above is a convenient shorthand for the following more explicit definition.

scala sc-compile-with:overview-async-context
def processData(using async: Async): Data =
  val file = new File("~/some/path")
  readDataEventually(file)(using async)

Mutation

Mutable variables and mutable data structures are also considered capabilities.
For instance, consider a method that creates a pair of functions for incrementing and reading a counter:

scala sc-compile-with:overview-mut-context
def counterOps =
  var counter: Int = 0
  val incr = () => counter += 1
  val current = () => counter
  (incr, current)

The function incr has type () ->{counter} Unit, where counter is the local variable defined in counterOps. This records the fact that the counter is updated when calling the function.

We distinguish read and write accesses to mutable data. A read access to a mutable data structure m charges a "fractional" read-only capability m.rd whereas a write access charges the full capability m. Separation checking ensures that targets to write accesses cannot be obscured through aliasing. This is analogous to borrow checking in Rust, but uses a different mechanism based on capabilities instead of regions.

Mutable data structures extend trait Mutable, which is another subtrait of Capability.
Methods that write to such data are marked with an update modifier. For instance, here is
a class for append-buffers:

scala sc-name:overview-buffer-context sc-compile-with:overview-mut-context
abstract class Buffer[T] extends Mutable {
  update def append(elem: T): Unit
  def apply(pos: Int): T
  def size: Int
}

The append method comes with an update modifier since it changes the contents of the Buffer.
By contrast, apply and size are regular methods that are guaranteed update-free.

Types are used to regulate calls to update methods. A reference of type Buffer only allows access to regular methods. If the reference has type Buffer^ it also allows access to update methods.

For instance, a copy method between buffers could be written like this:

scala sc-compile-with:overview-buffer-context
def copy[T](from: Buffer[T], to: Buffer[T]^): Unit =
  for i <- 0 until from.size do
    to.append(from(i))

The type of the Buffer arguments makes it clear which buffer is modified and which buffer is read-only. Note that the distinction between C and C^ applies to all types C extending trait Mutable. For other capability types the two forms are equivalent.

Global Capabilities

In traditional object capability systems, global capabilities are ruled out. Indeed, if we rely on controlling accesses simply by scoping rules, global capabilities don't make much sense since they allow unrestricted access everywhere.

But with tracked capabilities, we have another means to control access via tracked types. Consequently global capabilities can be allowed. For instance,
here is a Console object:

scala sc-hidden sc-name:overview-console-channel-context sc-compile-with:overview-cc-context
class File(path: String) extends SharedCapability
extension (file: File)
  def println(message: String): Unit = ()
scala sc-name:overview-console-context sc-compile-with:overview-console-channel-context
object Console extends SharedCapability:
  val in: File = new File("stdin")
  val out: File = new File("stdout")

Here, in, and out are of type File, so Console.in, and Console.out are global capabilities. A function () => Console.out.println("hi") would have type
() ->{Console.out} Unit. It could not be passed into a context expecting a pure function. A global object that refers to Console needs to declare that dependency in a uses clause.

scala sc-compile-with:overview-console-context
object SimpleLogger uses Console:
  def log(str: String): Unit = Console.out.println(str)

Allowing global capabilities like Console.out is quite useful since it means that we don't need to fundamentally change a system's architecture to make it capability-safe. In traditional capability systems all capabilities provided by the host system have to be passed as parameters into the main entry point and from there to all functions that need access. This usually requires a global refactoring of the code base and can lead to more complex code.

Summary

Scala 3's capabilities are both more convenient and more expressive than traditional ones. They are more convenient since using clauses allow to pass capabilities implicitly down a call chain and global capabilities reduce the need for such call chains in the first place. And they are more expressive, since tracked capabilities allow to describe and constrain the effects of computations. Furthermore, one can distinguish read-only and update capabilities and one can ensure that updates are only to unshared references.


index: index.md
subsection:

  • title: Reference
    directory: docs/reference

    Embed sidebar.reference.yml, performed by `generateScalaDocumentation` sbt task

  • title: Contributing
    directory: docs/contributing
    index: contributing/index.md
    subsection:
    • page: contributing/getting-started.md
    • page: contributing/setting-up-your-ide.md
    • index: contributing/issues/diagnosing-your-issue.md
      subsection:
      • page: contributing/issues/reproduce.md
      • page: contributing/issues/cause.md
      • page: contributing/issues/areas.md
    • index: contributing/debugging/debugging.md
      directory: debugging
      subsection:
      • page: contributing/debugging/ide-debugging.md
      • page: contributing/debugging/inspection.md
      • page: contributing/debugging/other-debugging.md
    • page: contributing/testing.md
    • page: contributing/scaladoc.md
    • page: contributing/community-build.md
    • page: contributing/sending-in-a-pr.md
    • page: contributing/cheatsheet.md
    • title: Procedures
      directory: procedures
      index: contributing/procedures/index.md
      subsection:
      • page: contributing/procedures/release.md
      • page: contributing/procedures/vulpix.md
      • page: contributing/procedures/contributing-to-stdlib.md
    • title: High Level Architecture
      directory: architecture
      index: contributing/architecture/index.md
      subsection:
      • page: contributing/architecture/lifecycle.md
      • page: contributing/architecture/context.md
      • page: contributing/architecture/phases.md
      • page: contributing/architecture/types.md
      • page: contributing/architecture/time.md
      • page: contributing/architecture/symbols.md
  • title: Internals
    directory: docs/internals
    index: internals/index.md
    subsection:
    • page: internals/backend.md
    • page: internals/classpaths.md
    • page: internals/contexts.md
    • page: internals/dotc-scalac.md
    • page: internals/higher-kinded-v2.md
    • page: internals/overall-structure.md
    • page: internals/explicit-nulls.md
    • page: internals/periods.md
    • page: internals/syntax.md
    • page: internals/type-system.md
    • page: internals/dotty-internals-1-notes.md
    • page: internals/debug-macros.md
    • page: internals/gadts.md
    • page: internals/coverage.md
    • page: internals/best-effort-compilation.md
    • page: internals/syntax-3.1.md
  • page: release-notes-0.1.2.md # Referenced from https://www.scala-lang.org/blog/2017/05/31/first-dotty-milestone-release.html
    hidden: true

index: reference/overview.md
subsection:

  • title: New Types
    index: reference/new-types/new-types.md
    subsection:
    • page: reference/new-types/intersection-types.md
    • page: reference/new-types/intersection-types-spec.md
      hidden: true
    • page: reference/new-types/union-types.md
    • page: reference/new-types/union-types-spec.md
      hidden: true
    • page: reference/new-types/type-lambdas.md
    • page: reference/new-types/type-lambdas-spec.md
      hidden: true
    • page: reference/new-types/match-types.md
    • page: reference/new-types/dependent-function-types.md
    • page: reference/new-types/dependent-function-types-spec.md
      hidden: true
    • page: reference/new-types/polymorphic-function-types.md
  • title: Enums
    index: reference/enums/enums-index.md
    subsection:
    • page: reference/enums/enums.md
    • page: reference/enums/adts.md
    • page: reference/enums/desugarEnums.md
  • title: Contextual Abstractions
    index: reference/contextual/contextual.md
    directory: contextual
    subsection:
    • page: reference/contextual/givens.md
    • page: reference/contextual/using-clauses.md
    • page: reference/contextual/context-bounds.md
    • page: reference/contextual/deferred-givens.md
    • page: reference/contextual/given-imports.md
    • page: reference/contextual/more-givens.md
    • page: reference/contextual/previous-givens.md
      hidden: true
    • page: reference/contextual/extension-methods.md
    • page: reference/contextual/right-associative-extension-methods.md
    • page: reference/contextual/type-classes.md
    • page: reference/contextual/derivation.md
    • page: reference/contextual/derivation-macro.md
    • page: reference/contextual/multiversal-equality.md
    • page: reference/contextual/context-functions.md
    • page: reference/contextual/context-functions-spec.md
      hidden: true
    • page: reference/contextual/conversions.md
    • page: reference/contextual/by-name-context-parameters.md
    • page: reference/contextual/relationship-implicits.md
  • title: Metaprogramming
    index: reference/metaprogramming/metaprogramming.md
    subsection:
    • page: reference/metaprogramming/inline.md
    • page: reference/metaprogramming/compiletime-ops.md
    • page: reference/metaprogramming/macros.md
    • page: reference/metaprogramming/macros-spec.md
      hidden: true
    • page: reference/metaprogramming/simple-smp.md # description of a simplified metaprogramming language, this might not be the best place for it
    • page: reference/metaprogramming/staging.md
    • page: reference/metaprogramming/reflection.md
    • page: reference/metaprogramming/tasty-inspect.md
  • title: Other New Features
    index: reference/other-new-features/other-new-features.md
    subsection:
    • page: reference/other-new-features/trait-parameters.md
    • page: reference/other-new-features/transparent-traits.md
    • page: reference/other-new-features/creator-applications.md
    • page: reference/other-new-features/export.md
    • page: reference/other-new-features/opaques.md
    • page: reference/other-new-features/opaques-details.md
    • page: reference/other-new-features/named-tuples.md
    • page: reference/other-new-features/open-classes.md
    • page: reference/other-new-features/parameter-untupling.md
    • page: reference/other-new-features/parameter-untupling-spec.md
      hidden: true
    • page: reference/other-new-features/generalized-method-syntax.md
    • page: reference/other-new-features/kind-polymorphism.md
    • page: reference/other-new-features/matchable.md
    • page: reference/other-new-features/threadUnsafe-annotation.md
    • page: reference/other-new-features/targetName.md
    • page: reference/other-new-features/control-syntax.md
    • page: reference/other-new-features/indentation.md
    • page: reference/other-new-features/safe-initialization.md
    • page: reference/other-new-features/type-test.md
    • page: reference/other-new-features/experimental-defs.md
    • page: reference/other-new-features/preview-defs.md
    • page: reference/other-new-features/binary-literals.md
    • page: reference/other-new-features/toplevel-definitions.md
    • page: reference/other-new-features/better-fors.md
    • page: reference/other-new-features/runtimeChecked.md
    • page: reference/other-new-features/into.md
  • title: Other Changed Features
    directory: changed-features
    index: reference/changed-features/changed-features.md
    subsection:
    • page: reference/changed-features/numeric-literals.md
    • page: reference/changed-features/structural-types.md
    • page: reference/changed-features/structural-types-spec.md
      hidden: true
    • page: reference/changed-features/operators.md
    • page: reference/changed-features/wildcards.md
    • page: reference/changed-features/imports.md
    • page: reference/changed-features/type-inference.md
    • page: reference/changed-features/implicit-resolution.md
    • page: reference/changed-features/implicit-conversions.md
    • page: reference/changed-features/implicit-conversions-spec.md
      hidden: true
    • page: reference/changed-features/overload-resolution.md
    • page: reference/changed-features/match-syntax.md
    • page: reference/changed-features/vararg-splices.md
    • page: reference/changed-features/pattern-bindings.md
    • page: reference/changed-features/pattern-matching.md
    • page: reference/changed-features/eta-expansion.md
    • page: reference/changed-features/eta-expansion-spec.md
      hidden: true
    • page: reference/changed-features/compiler-plugins.md
    • page: reference/changed-features/lazy-vals-init.md
    • page: reference/changed-features/main-functions.md
    • page: reference/changed-features/interpolation-escapes.md
  • title: Dropped Features
    index: reference/dropped-features/dropped-features.md
    subsection:
    • page: reference/dropped-features/delayed-init.md
    • page: reference/dropped-features/macros.md
    • page: reference/dropped-features/existential-types.md
    • page: reference/dropped-features/type-projection.md
    • page: reference/dropped-features/do-while.md
    • page: reference/dropped-features/procedure-syntax.md
    • page: reference/dropped-features/package-objects.md
    • page: reference/dropped-features/early-initializers.md
    • page: reference/dropped-features/class-shadowing.md
    • page: reference/dropped-features/class-shadowing-spec.md
      hidden: true
    • page: reference/dropped-features/limit22.md
    • page: reference/dropped-features/xml.md
    • page: reference/dropped-features/symlits.md
    • page: reference/dropped-features/auto-apply.md
    • page: reference/dropped-features/weak-conformance.md
    • page: reference/dropped-features/weak-conformance-spec.md
      hidden: true
    • page: reference/dropped-features/nonlocal-returns.md
    • page: reference/dropped-features/this-qualifier.md
    • page: reference/dropped-features/wildcard-init.md
  • title: Preview Features
    directory: preview
    index: reference/preview/overview.md
    subsection:
    • page: reference/preview/unrolled-defs.md
    • page: reference/preview/relaxed-lambdas.md
    • page: reference/preview/package-object-values.md
  • title: Experimental Features
    directory: experimental
    index: reference/experimental/overview.md
    subsection:
    • page: reference/experimental/better-fors.md
      hidden: true
    • page: reference/experimental/fewer-braces.md
      hidden: true
    • page: reference/experimental/generalized-method-syntax.md
      hidden: true
    • page: reference/experimental/named-tuples.md
      hidden: true
    • page: reference/experimental/canthrow.md
    • page: reference/experimental/erased-defs.md
    • page: reference/experimental/erased-defs-spec.md
      hidden: true
    • page: reference/experimental/named-typeargs.md
    • page: reference/experimental/named-typeargs-spec.md
      hidden: true
    • page: reference/experimental/numeric-literals.md
    • page: reference/experimental/explicit-nulls.md
    • page: reference/experimental/main-annotation.md
    • title: Capture Checking
      index: reference/experimental/capture-checking/cc.md
      subsection:
      • page: reference/experimental/capture-checking/overview.md
      • page: reference/experimental/capture-checking/basics.md
      • page: reference/experimental/capture-checking/classes.md
      • page: reference/experimental/capture-checking/polymorphism.md
      • page: reference/experimental/capture-checking/advanced.md
        hidden: true
      • page: reference/experimental/capture-checking/scoped-capabilities.md
      • page: reference/experimental/capture-checking/classifiers.md
      • page: reference/experimental/capture-checking/checked-exceptions.md
      • page: reference/experimental/capture-checking/mutability.md
      • page: reference/experimental/capture-checking/separation-checking.md
      • page: reference/experimental/capture-checking/safe.md
      • page: reference/experimental/capture-checking/how-to-use.md
      • page: reference/experimental/capture-checking/internals.md
    • page: reference/experimental/purefuns.md
    • page: reference/experimental/tupled-function.md
    • page: reference/experimental/modularity.md
    • page: reference/experimental/typeclasses.md
    • page: reference/experimental/runtimeChecked.md
      hidden: true
    • page: reference/experimental/quoted-patterns-with-polymorphic-functions.md
    • page: reference/experimental/sub-cases.md
    • page: reference/experimental/dedented-string-literals.md
    • page: reference/experimental/spec-strings.md
    • page: reference/experimental/inline-traits.md
    • page: reference/experimental/specialized-traits.md
    • page: reference/experimental/method-block-end-markers.md
  • page: reference/syntax.md
  • title: Language Versions
    index: reference/language-versions/language-versions.md
    subsection:
    • page: reference/language-versions/source-compatibility.md
    • page: reference/language-versions/binary-compatibility.md
  • page: reference/soft-modifier.md
  • page: reference/features-classification.md
  • title: Error Codes
    index: reference/error-codes/error-codes.md
    subsection:
    • page: reference/error-codes/E001.md
    • page: reference/error-codes/E002.md
    • page: reference/error-codes/E003.md
    • page: reference/error-codes/E004.md
    • page: reference/error-codes/E005.md
    • page: reference/error-codes/E006.md
    • page: reference/error-codes/E007.md
    • page: reference/error-codes/E008.md
    • page: reference/error-codes/E009.md
    • page: reference/error-codes/E010.md
    • page: reference/error-codes/E011.md
    • page: reference/error-codes/E012.md
    • page: reference/error-codes/E013.md
    • page: reference/error-codes/E014.md
    • page: reference/error-codes/E015.md
    • page: reference/error-codes/E016.md
    • page: reference/error-codes/E017.md
    • page: reference/error-codes/E018.md
    • page: reference/error-codes/E019.md
    • page: reference/error-codes/E020.md
    • page: reference/error-codes/E021.md
    • page: reference/error-codes/E022.md
    • page: reference/error-codes/E023.md
    • page: reference/error-codes/E024.md
    • page: reference/error-codes/E025.md
    • page: reference/error-codes/E026.md
    • page: reference/error-codes/E027.md
    • page: reference/error-codes/E028.md
    • page: reference/error-codes/E029.md
    • page: reference/error-codes/E030.md
    • page: reference/error-codes/E031.md
    • page: reference/error-codes/E032.md
    • page: reference/error-codes/E033.md
    • page: reference/error-codes/E034.md
    • page: reference/error-codes/E035.md
    • page: reference/error-codes/E036.md
    • page: reference/error-codes/E037.md
    • page: reference/error-codes/E038.md
    • page: reference/error-codes/E039.md
    • page: reference/error-codes/E040.md
    • page: reference/error-codes/E041.md
    • page: reference/error-codes/E042.md
    • page: reference/error-codes/E043.md
    • page: reference/error-codes/E044.md
    • page: reference/error-codes/E045.md
    • page: reference/error-codes/E046.md
    • page: reference/error-codes/E047.md
    • page: reference/error-codes/E048.md
    • page: reference/error-codes/E049.md
    • page: reference/error-codes/E050.md
    • page: reference/error-codes/E051.md
    • page: reference/error-codes/E052.md
    • page: reference/error-codes/E053.md
    • page: reference/error-codes/E054.md
    • page: reference/error-codes/E055.md
    • page: reference/error-codes/E056.md
    • page: reference/error-codes/E057.md
    • page: reference/error-codes/E058.md
    • page: reference/error-codes/E059.md
    • page: reference/error-codes/E060.md
    • page: reference/error-codes/E061.md
    • page: reference/error-codes/E062.md
    • page: reference/error-codes/E063.md
    • page: reference/error-codes/E064.md
    • page: reference/error-codes/E065.md
    • page: reference/error-codes/E066.md
    • page: reference/error-codes/E067.md
    • page: reference/error-codes/E068.md
    • page: reference/error-codes/E069.md
    • page: reference/error-codes/E070.md
    • page: reference/error-codes/E071.md
    • page: reference/error-codes/E072.md
    • page: reference/error-codes/E073.md
    • page: reference/error-codes/E074.md
    • page: reference/error-codes/E075.md
    • page: reference/error-codes/E076.md
    • page: reference/error-codes/E077.md
    • page: reference/error-codes/E078.md
    • page: reference/error-codes/E079.md
    • page: reference/error-codes/E080.md
    • page: reference/error-codes/E081.md
    • page: reference/error-codes/E082.md
    • page: reference/error-codes/E083.md
    • page: reference/error-codes/E084.md
    • page: reference/error-codes/E085.md
    • page: reference/error-codes/E086.md
    • page: reference/error-codes/E087.md
    • page: reference/error-codes/E088.md
    • page: reference/error-codes/E089.md
    • page: reference/error-codes/E090.md
    • page: reference/error-codes/E091.md
    • page: reference/error-codes/E092.md
    • page: reference/error-codes/E093.md
    • page: reference/error-codes/E094.md
    • page: reference/error-codes/E095.md
    • page: reference/error-codes/E096.md
    • page: reference/error-codes/E097.md
    • page: reference/error-codes/E098.md
    • page: reference/error-codes/E099.md
    • page: reference/error-codes/E100.md
    • page: reference/error-codes/E101.md
    • page: reference/error-codes/E102.md
    • page: reference/error-codes/E103.md
    • page: reference/error-codes/E104.md
    • page: reference/error-codes/E105.md
    • page: reference/error-codes/E106.md
    • page: reference/error-codes/E107.md
    • page: reference/error-codes/E108.md
    • page: reference/error-codes/E109.md
    • page: reference/error-codes/E110.md
    • page: reference/error-codes/E111.md
    • page: reference/error-codes/E112.md
    • page: reference/error-codes/E113.md
    • page: reference/error-codes/E114.md
    • page: reference/error-codes/E115.md
    • page: reference/error-codes/E116.md
    • page: reference/error-codes/E117.md
    • page: reference/error-codes/E118.md
    • page: reference/error-codes/E119.md
    • page: reference/error-codes/E120.md
    • page: reference/error-codes/E121.md
    • page: reference/error-codes/E122.md
    • page: reference/error-codes/E123.md
    • page: reference/error-codes/E124.md
    • page: reference/error-codes/E125.md
    • page: reference/error-codes/E126.md
    • page: reference/error-codes/E127.md
    • page: reference/error-codes/E128.md
    • page: reference/error-codes/E129.md
    • page: reference/error-codes/E130.md
    • page: reference/error-codes/E131.md
    • page: reference/error-codes/E132.md
    • page: reference/error-codes/E133.md
    • page: reference/error-codes/E134.md
    • page: reference/error-codes/E135.md
    • page: reference/error-codes/E136.md
    • page: reference/error-codes/E137.md
    • page: reference/error-codes/E138.md
    • page: reference/error-codes/E139.md
    • page: reference/error-codes/E140.md
    • page: reference/error-codes/E141.md
    • page: reference/error-codes/E142.md
    • page: reference/error-codes/E143.md
    • page: reference/error-codes/E144.md
    • page: reference/error-codes/E145.md
    • page: reference/error-codes/E146.md
    • page: reference/error-codes/E147.md
    • page: reference/error-codes/E148.md
    • page: reference/error-codes/E149.md
    • page: reference/error-codes/E150.md
    • page: reference/error-codes/E151.md
    • page: reference/error-codes/E152.md
    • page: reference/error-codes/E153.md
    • page: reference/error-codes/E154.md
    • page: reference/error-codes/E155.md
    • page: reference/error-codes/E156.md
    • page: reference/error-codes/E157.md
    • page: reference/error-codes/E158.md
    • page: reference/error-codes/E159.md
    • page: reference/error-codes/E160.md
    • page: reference/error-codes/E161.md
    • page: reference/error-codes/E162.md
    • page: reference/error-codes/E163.md
    • page: reference/error-codes/E164.md
    • page: reference/error-codes/E165.md
    • page: reference/error-codes/E166.md
    • page: reference/error-codes/E167.md
    • page: reference/error-codes/E168.md
    • page: reference/error-codes/E169.md
    • page: reference/error-codes/E170.md
    • page: reference/error-codes/E171.md
    • page: reference/error-codes/E172.md
    • page: reference/error-codes/E173.md
    • page: reference/error-codes/E174.md
    • page: reference/error-codes/E175.md
    • page: reference/error-codes/E176.md
    • page: reference/error-codes/E177.md
    • page: reference/error-codes/E178.md
    • page: reference/error-codes/E179.md
    • page: reference/error-codes/E180.md
    • page: reference/error-codes/E181.md
    • page: reference/error-codes/E182.md
    • page: reference/error-codes/E183.md
    • page: reference/error-codes/E184.md
    • page: reference/error-codes/E185.md
    • page: reference/error-codes/E186.md
    • page: reference/error-codes/E187.md
    • page: reference/error-codes/E188.md
    • page: reference/error-codes/E189.md
    • page: reference/error-codes/E190.md
    • page: reference/error-codes/E191.md
    • page: reference/error-codes/E192.md
    • page: reference/error-codes/E193.md
    • page: reference/error-codes/E194.md
    • page: reference/error-codes/E195.md
    • page: reference/error-codes/E196.md
    • page: reference/error-codes/E197.md
    • page: reference/error-codes/E198.md
    • page: reference/error-codes/E199.md
    • page: reference/error-codes/E200.md
    • page: reference/error-codes/E201.md
    • page: reference/error-codes/E202.md
    • page: reference/error-codes/E203.md
    • page: reference/error-codes/E204.md
    • page: reference/error-codes/E205.md
    • page: reference/error-codes/E206.md
    • page: reference/error-codes/E207.md
    • page: reference/error-codes/E208.md
    • page: reference/error-codes/E209.md
    • page: reference/error-codes/E210.md
    • page: reference/error-codes/E211.md
    • page: reference/error-codes/E212.md
    • page: reference/error-codes/E213.md
    • page: reference/error-codes/E214.md
    • page: reference/error-codes/E215.md
    • page: reference/error-codes/E216.md
    • page: reference/error-codes/E217.md
    • page: reference/error-codes/E218.md
    • page: reference/error-codes/E219.md
    • page: reference/error-codes/E220.md
    • page: reference/error-codes/E221.md
    • page: reference/error-codes/E222.md
    • page: reference/error-codes/E223.md
    • page: reference/error-codes/E224.md
    • page: reference/error-codes/E225.md
    • page: reference/error-codes/E226.md
    • page: reference/error-codes/E227.md
    • page: reference/error-codes/E228.md
    • page: reference/error-codes/E229.md
    • page: reference/error-codes/E230.md
    • page: reference/error-codes/E231.md
    • page: reference/error-codes/E232.md
    • page: reference/error-codes/E233.md
    • page: reference/error-codes/E234.md
    • page: reference/error-codes/E235.md

Docs Release Notes 0.1.2 (`docs/_docs/release-notes-0.1.2.md`)


layout: doc-page title: 0.1.2 release notes redirectFrom: /docs/release-notes/0.1.2.html

0.1.2 will be the first public release of Dotty.
Being the first one, these notes are incomplete.
This document is a work in progress until 0.1.2-final is released.
These notes are up-to-date based on 0.1.2-RC1 and will be updated
with changes that happen during the RC stabilization cycle.

Required Java Version

Dotty 0.1.2 targets Java 8. We don't have plans to add support for earlier versions of Java.

IDE support for Dotty

Reporting Bugs / Known Issues

Please file any bugs you encounter. If you’re unsure whether something is a bug,
please ask on the Dotty gitter channel.

Dotty Doc

Dotty has added support for Dotty Doc.
Actually, the dotty documentation site https://nightly.scala-lang.org/docs/ is generated by it.
Looks nice, doesn’t it?

#Other implemented features:

This release ships with the following features:

Contributors

The Dotty team and contributors have closed 750 issues and have merged a total of 1258 pull requests.

Concretely, according to

text
git ls-tree -r -z --name-only HEAD -- |egrep -z -Z -E '\.(scala)$'| xargs -0 -n1 git blame --line-porcelain |grep "^author "|sort|uniq -c|sort -nr

71 people contributed code, tests, and/or documentation to Dotty 0.1.2-RC1.
The following people have contributed to this release:

commits blame lines Name
4346 82017 Martin Odersky
1288 83070 Dmitry Petrashko
19 35382 Samuel Gruetter
826 20148 Felix Mulder
567 10454 Guillaume Martres
136 5311 liu fengyun
189 4449 Nicolas Stucki
21 3717 Sébastien Doeraene
30 1711 Ondrej Lhotak
33 1094 Enno Runne
47 735 Olivier Blanvillain
4 480 Valthor Halldorsson
7 343 Aleksander Boruch-Gruszecki
25 220 VladimirNik
3 186 Enno
8 143 Clemens Winter
16 133 Jason Zaugg
3 116 Miron Aseev
4 109 Shane Delmore
5 100 Alexander Myltsev
5 96 Abel Nieto
1 92 Dmitry Melnichenko
22 88 Jonathan Brachthäuser
5 87 Guillaume Massé
20 75 vsalvis
2 64 Tobias Schlatter
4 51 Ólafur Páll Geirsson
4 49 Sebastian Harko
2 48 Andrew Zurn
3 44 jvican
1 43 Jarrod Janssen
1 43 Igor Mielientiev
2 35 Thiago Pereira
5 32 Martijn Hoekstra
1 26 Bartosz Krasiński
1 24 Adam Trousdale
10 22 Aggelos Biboudis
12 20 Paolo G. Giarrusso
1 17 Jon-Anders Teigen
17 16 Vlad Ureche
1 16 Jyotman Singh
4 15 Lucas Burson
1 12 Markus Hauck
3 11 Varunram Ganesh
2 11 Reto Hablützel
3 10 Allan Renucci
4 9 Sarunas Valaskevicius
2 9 Nikolay.Tropin
1 9 Csongor Kiss
2 7 dos65
2 6 Varunram
6 5 Nada Amin
1 4 ruben
1 4 Kazuyoshi Kato
1 3 Jonathan Rodriguez
1 3 andreaTP
1 1 AlexSikia
3 0 Edmund Noble
2 0 jvican
3 0 Allan Renucci
3 0 Senia-psm
2 0 Lukas Rytz
2 0 Jan Christopher Vogt
2 0 Raymond Tay
1 0 Matthias Sperl
1 0 Herdy Handoko
1 0 Grzegorz Kossakowski
1 0 George Leontiev
1 0 Sandro Stucki
1 0 Adriaan Moors
1 0 Simon Hafner

Spec 01 Lexical Syntax (`docs/_spec/01-lexical-syntax.md`)


title: Lexical Syntax layout: default chapter: 1

Lexical Syntax

Scala source code consists of Unicode text.

The program text is tokenized as described in this chapter.
See the last section for special support for XML literals, which are parsed in XML mode.

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), modifier letters (Lm), letter numerals (Nl) and the two characters \u0024 ‘$’ and \u005F ‘_’.
  3. Digits ‘0’ | ... | ‘9’.
  4. Parentheses ‘(’ | ‘)’ | ‘[’ | ‘]’ | ‘{’ | ‘}’ .
  5. Delimiter characters ‘`’ | ‘'’ | ‘"’ | ‘.’ | ‘;’ | ‘,’ .
  6. Operator characters. These consist of all printable ASCII characters (\u0020 - \u007E) that are in none of the sets above, mathematical symbols (Sm) and other symbols (So).

Optional Braces

The principle of optional braces is that any keyword that can be followed by { can also be followed by an indented block, without needing an intervening :.
(Allowing an optional : would be counterproductive since it would introduce several ways to do the same thing.)

The lexical analyzer inserts indent and outdent tokens that represent regions of indented code at certain points.

In the context-free productions below we use the notation <<< ts >>> to indicate a token sequence ts that is either enclosed in a pair of braces { ts } or that constitutes an indented region indent ts outdent.
Analogously, the notation :<<< ts >>> indicates a token sequence ts that is either enclosed in a pair of braces { ts } or that constitutes an indented region indent ts outdent that follows a colon token.

A colon token reads as the standard colon ":" but is generated instead of it where colon is legal according to the context free syntax, but only if the previous token is an alphanumeric identifier, a backticked identifier, or one of the tokens this, super, new, ")", and "]".

text
colon         ::=  ':'    -- with side conditions explained above
 <<< ts >>>   ::=  ‘{’ ts ‘}’
                |  indent ts outdent
:<<< ts >>>   ::=  [nl] ‘{’ ts ‘}’
                |  colon indent ts outdent

Identifiers

ebnf
op            ::=  opchar {opchar}
varid         ::=  lower idrest
boundvarid    ::=  varid
                | ‘`’ varid ‘`’
alphaid       ::=  upper idrest
                |  varid
plainid       ::=  alphaid
                |  op
id            ::=  plainid
                |  ‘`’ { charNoBackQuoteOrNewline | escapeSeq } ‘`’
idrest        ::=  {letter | digit} [‘_’ op]
escapeSeq     ::= UnicodeEscape | charEscapeSeq
UnicodeEscape ::= ‘\’ ‘u’ {‘u’} hexDigit hexDigit hexDigit hexDigit
hexDigit      ::= ‘0’ | ... | ‘9’ | ‘A’ | ... | ‘F’ | ‘a’ | ... | ‘f’

There are three ways to form an identifier.
First, an identifier can start with a letter, followed by an arbitrary sequence of letters and digits.
This may be followed by underscore ‘_‘ characters and another string composed of either letters and digits or of operator characters.
Second, an identifier can start with an operator character followed by an arbitrary sequence of operator characters.
The preceding two forms are called plain identifiers.
Finally, an identifier may also be formed by an arbitrary string between backquotes (host systems may impose some restrictions on which strings are legal for identifiers).
The identifier then is composed of all characters excluding the backquotes themselves.

As usual, the longest match rule applies.
For instance, the string

scala
big_bob++=`def`

decomposes into the three identifiers big_bob, ++=, and
def.

The rules for pattern matching further distinguish between variable identifiers, which start with a lower case letter or _, and constant identifiers, which do not.

For this purpose, lower case letters include not only a-z, but also all characters in Unicode category Ll (lowercase letter), as well as all letters that have contributory property Other_Lowercase, except characters in category Nl (letter numerals), which are never taken as lower case.

The following are examples of variable identifiers:

text
x         maxIndex   p2p   empty_?
    `yield`   αρετη      _y    dot_product_*
    __system  _MAX_LEN_
    ªpple     ʰelper

Some examples of constant identifiers are

text
+    Object  $reserved  Džul    ǂnûm
    ⅰ_ⅲ  Ⅰ_Ⅲ     ↁelerious  ǃqhàà  ʹthatsaletter

The ‘$’ character is reserved for compiler-synthesized identifiers.
User programs should not define identifiers that contain ‘$’ characters.

Regular keywords

The following names are reserved words instead of being members of the syntactic class id of lexical identifiers.

text
abstract  case      catch     class     def       do        else
enum      export    extends   false     final     finally   for
given     if        implicit  import    lazy      match     new
null      object    override  package   private   protected return
sealed    super     then      throw     trait     true      try
type      val       var       while     with      yield
:         =         <-        =>        <:        >:        #
@         =>>       ?=>

Soft keywords

Additionally, the following soft keywords are reserved only in some situations.

text
as      derives      end      extension   infix   inline   opaque
open    transparent  using
|       *            +        -

A soft modifier is one of the identifiers infix, inline, opaque, open and transparent.

A soft keyword is a soft modifier, or one of as, derives, end, extension, using, |, +, -, *.

A soft modifier is treated as an actual modifier of a definition if it is followed by a hard modifier or a keyword combination starting a definition (def, val, var, type, given, class, trait, object, enum, case class, case object).
Between the two words, there may be a sequence of newline tokens and/or other soft modifiers.

Otherwise, soft keywords are treated as actual keywords in the following situations:

  • as, if it appears in a renaming import clause.
  • derives, if it appears after an extension clause or after the name and possibly parameters of a class, trait, object, or enum definition.
  • end, if it appears at the start of a line following a statement (i.e. definition or toplevel expression) and is followed on the same line by a single non-comment token that is:
    • one of the keywords for, given, if, match, new, this, throw, try, val, while, extension or
    • an identifier.
  • extension, if it appears at the start of a statement and is followed by ( or [.
  • inline, if it is followed by any token that can start an expression.
  • using, if it appears at the start of a parameter or argument list.
  • |, if it separates two patterns in an alternative.
  • +, -, if they appear in front of a type parameter.
  • *, if it appears in a wildcard import, or if it follows the type of a parameter, or if it appears in a vararg splice x*.

Everywhere else, a soft keyword is treated as a normal identifier.

When one needs to access Java identifiers that are reserved words in Scala, use backquote-enclosed strings.
For instance, the statement Thread.yield() is illegal, since yield is a reserved word in Scala.
However, here's a work-around: Thread.`yield`()

Newline Characters

ebnf
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 and is not a leading infix operator.
  3. The token appears in a region where newlines are enabled.

The tokens that can terminate a statement are: literals, identifiers and the following delimiters and reserved words:

text
this    null    true    false    return    type    given    <xml-start>
_       )       ]       }        outdent

The tokens that can begin a statement are all Scala tokens except the following delimiters and reserved words:

text
catch    do      else    extends    finally    forSome    macro
match    then    with    yield
,    .    ;    :    =    =>    <-    <:    <%    >:    #    =>>    ?=>
)    ]    }    outdent

A leading infix operator is a symbolic identifier such as +, or approx_==, or an identifier in backticks that:

  • starts a new line, and
  • is not following a blank line, and
  • is followed by at least one whitespace character (including new lines) and a token that can start an expression.

Furthermore, if the operator appears on its own line, the next line must have at least the same indentation width as the operator.

Newlines are enabled in:

  1. all of a Scala source file, except for nested regions where newlines are disabled, and
  2. the interval between matching { and } brace tokens, except for nested regions where newlines are disabled.

Newlines are disabled in:

  1. the interval between matching ( and ) parenthesis tokens, except for nested regions where newlines are enabled, and
  2. the interval between matching [ and ] bracket tokens, except for nested regions 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.

Note that the brace characters of {...} escapes in XML and string literals are not tokens, and therefore do not enclose a region where newlines are enabled.

Normally, only a single nl token is inserted between two consecutive non-newline tokens which are on different lines, even if there are multiple lines between the two tokens.
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 here) contains productions where optional 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.
These positions 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):

A single new line token is accepted

  • in front of an opening brace ‘{’, if that brace is a legal continuation of the current statement or expression,
  • after an infix operator, if the first token on the next line can start an expression,
  • in front of a parameter clause, and
  • after an annotation.

The newline tokens between the two lines are not treated as statement separators.

scala
if (x > 0)
  x = x - 1

while (x > 0)
  x = x / 2

for (x <- 1 to 10)
  println(x)

type
  IntList = List[Int]
scala
new Iterator[Int]
{
  private var x = 0
  def hasNext = true
  def next = { x += 1; x }
}

With an additional newline character, the same code is interpreted as an object creation followed by a local block:

scala
new Iterator[Int]

{
  private var x = 0
  def hasNext = true
  def next = { x += 1; x }
}
scala
x < 0 ||
  x > 10

With an additional newline character, the same code is interpreted as two expressions:

scala
x < 0 ||

  x > 10
scala
def func(x: Int)
        (y: Int) = x + y

With an additional newline character, the same code is interpreted as an abstract method definition and a syntactically illegal statement:

scala
def func(x: Int)

        (y: Int) = x + y
scala
@serializable
protected class Data { ... }

With an additional newline character, the same code is interpreted as an attribute and a separate statement (which is syntactically illegal).

scala
@serializable

protected class Data { ... }

Literals

There are literals for integer numbers, floating point numbers, characters, booleans, strings.
The syntax of these literals is in each case as in Java.

ebnf
Literal  ::=  [‘-’] integerLiteral
           |  [‘-’] floatingPointLiteral
           |  booleanLiteral
           |  characterLiteral
           |  stringLiteral
           |  interpolatedString
           |  ‘null’

Integer Literals

ebnf
integerLiteral   ::=  (decimalNumeral | hexNumeral | binaryNumeral) [‘L’ | ‘l’]
decimalNumeral   ::=  ‘0’ | digit [{digit | ‘_’} digit]
hexNumeral       ::=  ‘0’ (‘x’ | ‘X’) hexDigit [{hexDigit | ‘_’} hexDigit]
binaryNumeral    ::=  ‘0’ (‘b’ | ‘B’) binaryDigit [{binaryDigit | ‘_’} binaryDigit]

Values of type Int are all integer numbers between $-2^{31}$ and $2^{31}-1$, inclusive.
Values of type Long are all integer numbers between $-2^{63}$ and
$2^{63}-1$, inclusive.
A compile-time error occurs if an integer literal denotes a number outside these ranges.

Integer literals are usually of type Int, or of type Long when followed by a L or l suffix.
(Lowercase l is deprecated for reasons of legibility.)

However, if the expected type pt 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 ´-2^7´ to ´2^7-1´
Short ´-2^{15}´ to ´2^{15}-1´
Char ´0´ to ´2^{16}-1´

The digits of a numeric literal may be separated by arbitrarily many underscores for purposes of legibility.

scala
0           21_000      0x7F        -42L        0xFFFF_FFFF        0b0100_0010

Floating Point Literals

ebnf
floatingPointLiteral  ::=  [decimalNumeral] ‘.’ digit [{digit | ‘_’} digit] [exponentPart] [floatType]
                        |  decimalNumeral exponentPart [floatType]
                        |  decimalNumeral floatType
exponentPart          ::=  (‘E’ | ‘e’) [‘+’ | ‘-’] digit [{digit | ‘_’} digit]

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 consists of all IEEE 754 64-bit double-precision binary floating point values.

If 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 tokens.

scala
0.0        1e30f      3.14159f      1.0e-100      .1

The phrase 1.toString parses as three different tokens: the integer literal 1, a ., and the identifier toString.

1. is not a valid floating point literal because the mandatory digit after the . is missing.

Boolean Literals

ebnf
booleanLiteral  ::=  ‘true’ | ‘false’

The boolean literals true and false are members of type Boolean.

Character Literals

ebnf
characterLiteral  ::=  ‘'’ (charNoQuoteOrNewline | escapeSeq) ‘'’

A character literal is a single character enclosed in quotes.
The character can be any Unicode character except the single quote delimiter or \u000A (LF) or \u000D (CR); or any Unicode character represented by an
escape sequence.

scala
'a'    '\u0041'    '\n'    '\t'

String Literals

ebnf
stringLiteral  ::=  ‘"’ {stringElement} ‘"’
stringElement  ::=  charNoDoubleQuoteOrNewline | escapeSeq

A string literal is a sequence of characters in double quotes.
The characters can be any Unicode character except the double quote delimiter or \u000A (LF) or \u000D (CR); or any Unicode character represented by an escape sequence.

If the string literal contains a double quote character, it must be escaped using
"\"".

The value of a string literal is an instance of class String.

scala
"Hello, world!\n"
"\"Hello,\" replied the world."

Multi-Line String Literals

ebnf
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 contain three or more consecutive quote characters only at the very end.
Characters must not necessarily be printable; newlines or other control characters are also permitted.
Escape sequences are not processed, except for Unicode escapes (this is deprecated since 2.13.2).

scala
"""the present string
     spans three
     lines."""

This would produce the string:

text
the present string
     spans three
     lines.

The Scala library contains a utility method stripMargin which can be used to strip leading whitespace from multi-line strings.
The expression

scala
"""the present string
   |spans three
   |lines.""".stripMargin

evaluates to

text
the present string
spans three
lines.

Method stripMargin is defined in class
scala.collection.StringOps.

Interpolated string

ebnf
interpolatedString     ::= alphaid ‘"’ {[‘\’] interpolatedStringPart | ‘\\’ | ‘\"’} ‘"’
                         | alphaid ‘"""’ {[‘"’] [‘"’] char \ (‘"’ | ‘$’) | escape} {‘"’} ‘"""’
interpolatedStringPart ::= printableChar \ (‘"’ | ‘$’ | ‘\’) | escape
escape                 ::= ‘$$’
                         | ‘$"’
                         | ‘$’ alphaid
                         | ‘$’ BlockExpr
alphaid                ::= upper idrest
                         |  varid

An interpolated string consists of an identifier starting with a letter immediately followed by a string literal.
There may be no whitespace characters or comments between the leading identifier and the opening quote " of the string.
The string literal in an interpolated string can be standard (single quote) or multi-line (triple quote).

Inside an interpolated string none of the usual escape characters are interpreted no matter whether the string literal is normal (enclosed in single quotes) or multi-line (enclosed in triple quotes).
Note that the sequence \" does not close a normal string literal (enclosed in single quotes).

There are three forms of dollar sign escape.
The most general form encloses an expression in ${ and }, i.e. ${expr}.
The expression enclosed in the braces that follow the leading $ character is of syntactical category BlockExpr.
Hence, it can contain multiple statements, and newlines are significant.
Single ‘$’-signs are not permitted in isolation in an interpolated string.
A single ‘$’-sign can still be obtained by doubling the ‘$’ character: ‘$$’.
A single ‘"’-sign can be obtained by the sequence ‘$"’.

The simpler form consists of a ‘$’-sign followed by an identifier starting with a letter and followed only by letters, digits, and underscore characters, e.g., $id.
The simpler form is expanded by putting braces around the identifier, e.g., $id is equivalent to ${id}.
In the following, unless we explicitly state otherwise, we assume that this expansion has already been performed.

The expanded expression is type checked normally.
Usually, StringContext will resolve to the default implementation in the scala package, but it could also be user-defined.
Note that new interpolators can also be added through implicit conversion of the built-in scala.StringContext.

One could write an extension

scala
implicit class StringInterpolation(s: StringContext) {
  def id(args: Any*) = ???
}

Escape Sequences

The following character escape sequences are recognized in character and string literals.

charEscapeSeq unicode name char
‘\‘ ‘b‘ \u0008 backspace BS
‘\‘ ‘t‘ \u0009 horizontal tab HT
‘\‘ ‘n‘ \u000a linefeed LF
‘\‘ ‘f‘ \u000c form feed FF
‘\‘ ‘r‘ \u000d carriage return CR
‘\‘ ‘s‘ \u0020 space
‘\‘ ‘"‘ \u0022 double quote "
‘\‘ ‘'‘ \u0027 single quote '
‘\‘ ‘\‘ \u005c backslash \

In addition, Unicode escape sequences of the form \uxxxx, where each x is a hex digit are recognized in character and string literals.

It is a compile time error if a backslash character in a character or string literal does not start a valid escape sequence.

Whitespace and Comments

Tokens may be separated by whitespace characters and/or comments.
Comments come 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-line comments may be nested, but are required to be properly nested.
Therefore, a comment like /* /* */ will be rejected as having an unterminated comment.

Trailing Commas in Multi-line Expressions

If a comma (,) is followed immediately, ignoring whitespace, by a newline and a closing parenthesis ()), bracket (]), or brace (}), then the comma is treated as a "trailing comma" and is ignored.
For example:

scala
foo(
  23,
  "bar",
  true,
)

XML mode

In order to allow literal inclusion of XML fragments, lexical analysis switches from Scala mode to XML mode when encountering an opening angle bracket ‘<’ in the following circumstance:
The ‘<’ must be preceded either by whitespace, an opening parenthesis or an opening brace and immediately followed by a character starting an XML name.

ebnf
( 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 successfully 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 successfully 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 are interpreted as text.

The following value definition uses an XML literal with two embedded Scala expressions:

scala
val b = <book>
          <title>The Scala Language Specification</title>
          <version>{scalaBook.version}</version>
          <authors>{scalaBook.authors.mkList("", ", ", "")}</authors>
        </book>

Spec 02 Identifiers Names And Scopes (`docs/_spec/02-identifiers-names-and-scopes.md`)


title: Identifiers, Names & Scopes layout: default chapter: 2

Identifiers, Names and Scopes

Names in Scala identify types, values, methods, and classes which are collectively called entities.
Names are introduced by local
definitions,
inheritance,
import clauses, or
package clauses
which are collectively called bindings.

Bindings of different kinds have precedence defined on them:

  1. Definitions that are local, inherited, or made available by a package clause and also defined in the same compilation unit as the reference to them, have the highest precedence.
  2. Explicit imports have the next highest precedence.
  3. Wildcard imports have the next highest precedence.
  4. Definitions made available by a package clause, but not also defined in the same compilation unit as the reference to them, as well as imports which are supplied by the compiler but not explicitly written in source code, have the lowest precedence.

There are two different name spaces, one for types and one for terms.
The same name may designate a type and a term, depending on the context where the name is used.

A binding has a scope in which the entity defined by a single
name can be accessed using 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 or lower precedence in outer scopes.

Note that shadowing is only a partial order.
In the following example, neither binding of x shadows the other.
Consequently, the reference to x in the last line of the block is ambiguous.

scala
val x = 1
locally {
  import p.X.x
  x
}

A reference to an unqualified (type- or term-) identifier ´x´ is bound by the unique binding, 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 namespace.

It is an error if no such binding exists.
If ´x´ is bound by an import clause, then the simple 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, then ´x´ refers to the entity introduced by that binding.
In that case, the type of ´x´ is the type of the referenced entity.

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 is an error if ´T´ is not a value type.
The type of ´e.x´ is specified as a type designator.

Binding precedence implies that the way source is bundled in files affects name resolution.
In particular, imported names have higher precedence than names, defined in other files, that might otherwise be visible because they are defined in either the current package or an enclosing package.

Note that a package definition is taken as lowest precedence, since packages are open and can be defined across arbitrary compilation units.

scala
package util {
  import scala.util
  class Random
  object Test extends App {
    println(new util.Random)  // scala.util.Random
  }
}

The compiler supplies imports in a preamble to every source file.
This preamble conceptually has the following form, where braces indicate nested scopes:

scala
import java.lang.*
{
  import scala.*
  {
    import Predef.*
    { /* source */ }
  }
}

These imports are taken as lowest precedence, so that they are always shadowed by user code, which may contain competing imports and definitions.
They also increase the nesting depth as shown, so that later imports shadow earlier ones.

As a convenience, multiple bindings of a type identifier to the same underlying type is permitted.
This is possible when import clauses introduce a binding of a member type alias with the same binding precedence, typically through wildcard imports.
This allows redundant type aliases to be imported without introducing an ambiguity.

scala
object X { type T = annotation.tailrec }
object Y { type T = annotation.tailrec }
object Z {
  import X.*, Y.*, annotation.tailrec as T  // OK, all T mean tailrec
  @T def f: Int = { f ; 42 }                // error, f is not tail recursive
}

Similarly, imported aliases of names introduced by package statements are allowed, even though the names are strictly ambiguous:

scala
// c.scala
package p { class C }

// xy.scala
import p.*
package p { class X extends C }
package q { class Y extends C }

The reference to C in the definition of X is strictly ambiguous because C is available by virtue of the package clause in a different file, and can't shadow the imported name.
But because the references are the same, the definition is taken as though it did shadow the import.

Example

Assume the following two definitions of objects named X in packages p and q in separate compilation units.

scala
package p {
  object X { val x = 1; val y = 2 }
}

package q {
  object X { val x = true; val y = false }
}

The following program illustrates different kinds of bindings and precedences between them.

scala
package p {                     // `X' bound by package clause
  import Console.*              // `println' bound by wildcard import
  object Y {
    println(s"L4: $X")          // `X' refers to `p.X' here
    locally {
      import q.*                // `X' bound by wildcard import
      println(s"L7: $X")        // `X' refers to `q.X' here
      import X.*                // `x' and `y' bound by wildcard import
      println(s"L9: $x")        // `x' refers to `q.X.x' here
      locally {
        val x = 3               // `x' bound by local definition
        println(s"L12: $x")     // `x' refers to constant `3' here
        locally {
          import q.X.*          // `x' and `y' bound by wildcard import
//        println(s"L15: $x")   // reference to `x' is ambiguous here
          import X.y            // `y' bound by explicit import
          println(s"L17: $y")   // `y' refers to `q.X.y' here
          locally {
            val x = "abc"       // `x' bound by local definition
            import p.X.*        // `x' and `y' bound by wildcard import
//          println(s"L21: $y") // reference to `y' is ambiguous here
            println(s"L22: $x") // `x' refers to string "abc" here
          }
        }
      }
    }
  }
}

Spec 03 Types (`docs/_spec/03-types.md`)


title: Types layout: default chapter: 3

Types

text
/* Detailed source-code truncated for AI context efficiency. */

The above grammer describes the concrete syntax of types that can be written in user code.
Semantic operations on types in the Scala type system are better defined in terms of internal types, which are desugared from the concrete type syntax.

Internal Types

The following abstract grammar defines the shape of internal types.
In this specification, unless otherwise noted, "types" refer to internal types.
Internal types abstract away irrelevant details such as precedence and grouping, and contain shapes of types that cannot be directly expressed using the concrete syntax.
They also contain simplified, decomposed shapes for complex concrete syntax types, such as refined types.

text
/* Detailed source-code truncated for AI context efficiency. */

Translation of Concrete Types into Internal Types

Concrete types are recursively translated, or desugared, into internal types.
Most shapes of concrete types have a one-to-one translation to shapes of internal types.
We elaborate hereafter on the translation of the other ones.

Infix Types

ebnf
InfixType     ::=  CompoundType {id [nl] CompoundType}

A concrete infix type ´T_1´ op ´T_2´ consists of an infix operator op which gets applied to two type operands ´T_1´ and ´T_2´.
The type is translated to the internal type application op´[T_1, T_2]´.
The infix operator op may be an arbitrary identifier.

Type operators follow the same precedence and associativity as term operators.
For example, A + B * C parses as A + (B * C) and A | B & C parses as A | (B & C).
Type operators ending in a colon ‘:’ are right-associative; all other operators are left-associative.

In a sequence of consecutive type infix operations ´t_0 , \mathit{op} , t_1 , \mathit{op_2} , ... , \mathit{op_n} , t_n´, all operators ´\mathit{op}_1, ..., \mathit{op}_n´ must have the same associativity.
If they are all left-associative, the sequence is interpreted as ´(... (t_0 \mathit{op_1} t_1) \mathit{op_2} ...) \mathit{op_n} t_n´, otherwise it is interpreted as ´t_0 \mathit{op_1} (t_1 \mathit{op_2} ( ... \mathit{op_n} t_n) ...)´.

Under -source:future, if the type name is alphanumeric and the target type is not marked infix, a deprecation warning is emitted.

The type operators | and & are not really special.
Nevertheless, unless shadowed, they resolve to the fundamental type aliases scala.| and scala.&, which represent union and intersection types, respectively.

Function Types

ebnf
Type              ::=  FunTypeArgs ‘=>’ Type
FunTypeArgs       ::=  InfixType
                    |  ‘(’ [ FunArgTypes ] ‘)’
                    |  FunParamClause
FunArgTypes       ::=  FunArgType { ‘,’ FunArgType }
FunArgType        ::=  Type
                    |  ‘=>’ Type
FunParamClause    ::=  ‘(’ TypedFunParam {‘,’ TypedFunParam } ‘)’
TypedFunParam     ::=  id ‘:’ Type

The concrete function type ´(T_1, ..., T_n) \Rightarrow R´ represents the set of function values that take arguments of types ´T_1, ..., Tn´ and yield results of type ´R´.
The case of exactly one argument type ´T \Rightarrow R´ is a shorthand for ´(T) \Rightarrow R´.
An argument type of the form ´\Rightarrow T´ represents a call-by-name parameter of type ´T´.

Function types associate to the right, e.g. ´S \Rightarrow T \Rightarrow R´ is the same as ´S \Rightarrow (T \Rightarrow R)´.

Function types are covariant in their result type and contravariant in their argument types.

Function types translate into internal class types that define an apply method.
Specifically, the ´n´-ary function type ´(T_1, ..., T_n) \Rightarrow R´ translates to the internal class type scala.Function´_n´[´T_1´, ..., ´T_n´, ´R´].
In particular ´() \Rightarrow R´ is a shorthand for class type scala.Function´_0´[´R´].

Such class types behave as if they were instances of the following trait:

scala
trait Function´_n´[-´T_1´, ..., -´T_n´, +´R´]:
  def apply(´x_1´: ´T_1´, ..., ´x_n´: ´T_n´): ´R´

Their exact supertype and implementation can be consulted in the function classes section of the standard library page in this document.

Dependent function types are function types whose parameters are named and can referred to in result types.
In the concrete type ´(x_1: T_1, ..., x_n: T_n) \Rightarrow R´, ´R´ can refer to the parameters ´x_i´, notably to form path-dependent types.
It translates to the internal refined type

scala
scala.Function´_n´[´T_1´, ..., ´T_n´, ´S´] {
  def apply(´x_1´: ´T_1´, ..., ´x_n´: ´T_n´): ´R´
}

where ´S´ is the least super type of ´R´ that does not mention any of the ´x_i´.

Polymorphic function types are function types that take type arguments.
Their result type must be a function type.
In the concrete type ´[a_1 >: L_1 <: H_1, ..., a_n >: L_1 <: H_1] => (T_1, ..., T_m) => R´, the types ´T_j´ and ´R´ can refer to the type parameters ´a_i´.
It translates to the internal refined type

scala
scala.PolyFunction {
  def apply[´a_1 >: L_1 <: H_1, ..., a_n >: L_1 <: H_1´](´x_1´: ´T_1´, ..., ´x_n´: ´T_n´): ´R´
}

Tuple Types

ebnf
SimpleType1           ::=  ...
                        |  ‘(’ TypesOrWildcards ‘)’

A tuple type ´(T_1, ..., T_n)´ where ´n \geq 2´ is sugar for the type ´T_1´ *: ... *: ´T_n´ *: scala.EmptyTuple, which is itself a series of nested infix types which are sugar for *:[´T_1´, *:[´T_2´, ... *:[´T_n´, scala.EmptyTuple]]].
The ´T_i´ can be wildcard type arguments.

Notes:

  • (´T_1´) is the type ´T_1´, and not ´T_1´ *: scala.EmptyTuple (´T_1´ cannot be a wildcard type argument in that case).
  • () is not a valid type (i.e. it is not desugared to scala.EmptyTuple).

Concrete Refined Types

ebnf
RefinedType           ::=  AnnotType {[nl] Refinement}
SimpleType1           ::=  ...
                        |  Refinement
Refinement            ::=  :<<< [RefineDef] {semi [RefineDef]} >>>

RefineDef             ::=  ‘val’ ValDef
                        |  ‘def’ DefDef
                        |  ‘type’ {nl} TypeDef

In the concrete syntax of types, refinements can contain several refined definitions.
They must all be abstract.
Moreover, the refined definitions can refer to each other as well as to members of the parent type, i.e., they have access to this.

In the internal types, each refinement defines exactly one refined definition, and references to this must be made explicit in a recursive type.

The conversion from the concrete syntax to the abstract syntax works as follows:

  1. Create a fresh recursive this name ´\alpha´.
  2. Replace every implicit or explicit reference to this in the refinement definitions by ´\alpha´.
  3. Create nested refined types, one for every refined definition.
  4. Unless ´\alpha´ was never actually used, wrap the result in a recursive type { ´\alpha´ => ´...´ }.

Concrete Match Types

ebnf
MatchType             ::=  InfixType ‘match’ <<< TypeCaseClauses >>>
TypeCaseClauses       ::=  TypeCaseClause { TypeCaseClause }
TypeCaseClause        ::=  ‘case’ (InfixType | ‘_’) ‘=>’ Type [semi]

In the concrete syntax of match types, patterns are arbitrary InfixTypes, and there is no explicit notion of type capture.
In the abstract syntax, however, captures are made explicit and can only appear as arguments to TypeCaseAppliedPatterns.

If the concrete pattern is _, its conversion is the internal type scala.Any.
If it is a concrete InfixType, it is first converted to an internal type ´P´.
If ´P´ is not a ParameterizedType, then use ´P´ as the internal pattern.
Otherwise, ´P´ is recursively converted into a TypeCasePattern as follows:

  1. If ´P´ is a WildcardTypeArg of the form ? >: ´L´ <: ´H´, return a TypeCapture of the form _ >: ´L´ <: ´H´.
  2. If ´P´ is a direct type designator ´t´ whose name starts with a lowercase and was not written using backticks, return a TypeCapture ´t´ >: ´L´ <: ´H´ where >: ´L´ <: ´H´ is the declared type definition of ´t´.
  3. If ´P´ is a ParameterizedType of the form ´T´[´T_1´, ..., ´T_n´]:
  4. Recursively convert each ´T_i´ into a pattern ´P_i´.
  5. If ´P_i´ is a Type for all ´i´, return ´P´.
  6. Otherwise, return the TypeCaseAppliedPattern ´T´[´P_1´, ..., ´P_n´].
  7. Otherwise, return ´P´.

This conversion ensures that every TypeCaseAppliedPattern recursively contains at least one TypeCapture.
Moreover, at the top level, the pattern is never a TypeCapture: all TypeCaptures are nested within a TypeCaseAppliedPattern.

The bound of the internal MatchType is always <: scala.Any by default.
It can be overridden in a type member definition.

Concrete Type Lambdas

ebnf
TypeLambda            ::= TypeLambdaParams ‘=>>’ Type
TypeLambdaParams      ::=  ‘[’ TypeLambdaParam {‘,’ TypeLambdaParam} ‘]’
TypeLambdaParam       ::=  {Annotation} (id | ‘_’) [TypeParamClause] TypeBounds
TypeParamClause       ::=  ‘[’ VariantTypeParam {‘,’ VariantTypeParam} ‘]’
VariantTypeParam      ::=  {Annotation} [‘+’ | ‘-’] (id | ‘_’) [TypeParamClause] TypeBounds

At the top level of concrete type lambda parameters, variance annotations are not allowed.
However, in internal types, all type lambda parameters have explicit variance annotations.

When translating a concrete type lambda into an internal one, the variance of each type parameter is inferred from its usages in the body of the type lambda.

Definitions

From here onwards, we refer to internal types by default.

Kinds

The Scala type system is fundamentally higher-kinded.
Types are either proper types, type constructors or poly-kinded types.

  • Proper types are the types of terms.
  • Type constructors are type-level functions from types to types.
  • Poly-kinded types can take various kinds.

All types live in a single lattice with respect to a conformance relationship ´<:´.
The top type is AnyKind and the bottom type is Nothing: all types conform to AnyKind, and Nothing conforms to all types.
They can be referred to with the fundamental type aliases scala.AnyKind and scala.Nothing, respectively.

Types can be concrete or abstract.
An abstract type ´T´ always has lower and upper bounds ´L´ and ´H´ such that ´L >: T´ and ´T <: H´.
A concrete type ´T´ is considered to have itself as both lower and upper bound.

The kind of a type is indicated by its (transitive) upper bound:

  • A type ´T <:´ scala.Any is a proper type.
  • A type ´T <: K´ where ´K´ is a type lambda (of the form [´\pm a_1 >: L_1 <: H_1´, ..., ´\pm a_n >: L_n <: H_n´] =>> ´U´) is a type constructor.
  • Other types are poly-kinded; they are neither proper types nor type constructors.

As a consequece, AnyKind itself is poly-kinded.
Nothing is universally-kinded: it has all kinds at the same time, since it conforms to all types.

With this representation, it is rarely necessary to explicitly talk about the kinds of types.
Usually, the kinds of types are implicit through their bounds.

Another way to look at it is that type bounds are kinds.
They represent sets of types: ´>: L <: H´ denotes the set of types ´T´ such that ´L <: T´ and ´T <: H´.
A set of types can be seen as a type of types, i.e., as a kind.

Conventions

Type bounds are formally always of the form ´>: L <: H´.
By convention, we can omit either of both bounds in writing.

  • When omitted, the lower bound ´L´ is Nothing.
  • When omitted, the higher bound ´H´ is Any (not AnyKind).

These conventions correspond to the defaults in the concrete syntax.

Proper Types

Proper types are also called value types, as they represent sets of values.

Stable types are value types that contain exactly one non-null value.
Stable types can be used as prefixes in named designator types.
The stable types are

  • designator types referencing a stable term,
  • this types,
  • super types,
  • literal types,
  • recursive this types, and
  • skolem types.

Every stable type ´T´ is concrete and has an underlying type ´U´ such that ´T <: U´.

Type Constructors

To each type constructor corresponds an inferred type parameter clause which is computed as follows:

  • For a type lambda, its type parameter clause (including variance annotations).
  • For a polymorphic class type, the type parameter clause of the referenced class definition.
  • For a non-class type designator, the inferred clause of its upper bound.

Type Definitions

A type definition ´D´ represents the right-hand-side of a type member definition or the bounds of a type parameter.
It is either:

  • a type alias of the form ´= U´, or
  • an abstract type definition with bounds ´>: L <: H´.

All type definitions have a lower bound ´L´ and an upper bound ´H´, which are types.
For type aliases, ´L = H = U´.

The type definition of a type parameter is never a type alias.

Types

Type Lambdas

ebnf
TypeLambda     ::=  ‘[‘ TypeParams ‘]‘ ‘=>>‘ Type
TypeParams     ::=  TypeParam {‘,‘ TypeParam}
TypeParam      ::=  ParamVariance id TypeBounds
ParamVariance  ::=  ε | ‘+‘ | ‘-‘

A type lambda of the form [´\pm a_1 >: L_1 <: H_1´, ..., ´\pm a_n >: L_n <: H_n´] =>> ´U´ is a direct representation of a type constructor with ´n´ type parameters.
When applied to ´n´ type arguments that conform to the specified bounds, it produces another type ´U´.
Type lambdas are always concrete types.

The scope of a type parameter extends over the result type ´U´ as well as the bounds of the type parameters themselves.

All type constructors conform to some type lambda.

The type bounds of the parameters of a type lambda are in contravariant position, while its result type is in covariant position.
If some type constructor ´T <:´ [´\pm a_1 >: L_1 <: H_1´, ..., ´\pm a_n >: L_n <: H_n´] =>> ´U´, then ´T´'s ´i´th type parameter bounds contain the bounds ´>: L_i <: H_i´, and its result type conforms to ´U´.

Note: the concrete syntax of type lambdas does not allow to specify variances for type parameters.
Instead, variances are inferred from the body of the lambda to be as general as possible.

Example

scala
type Lst = [T] =>> List[T] // T is inferred to be covariant with bounds >: Nothing <: Any
type Fn = [A <: Seq[?], B] =>> (A => B) // A is inferred to be contravariant, B covariant

val x: Lst[Int] = List(1) // ok, Lst[Int] expands to List[Int]
val f: Fn[List[Int], Int] = (x: List[Int]) => x.head // ok

val g: Fn[Int, Int] = (x: Int) => x // error: Int does not conform to the bound Seq[?]

def liftPair[F <: [T] =>> Any](f: F[Int]): Any = f
liftPair[Lst](List(1)) // ok, Lst <: ([T] =>> Any)

Designator Types

ebnf
DesignatorType    ::=  Prefix ‘.‘ id
Prefix            ::=  Type
                    |  PackageRef
                    |  ε
PackageRef        ::=  id {‘.‘ id}

A designator type (or designator for short) is a reference to a definition.
Term designators refer to term definitions, while type designators refer to type definitions.

In the abstract syntax, the id retains whether it is a term or type.
In the concrete syntax, an id refers to a type designator, while id.type refers to a term designator.
In that context, term designators are often called singleton types.

Designators with an empty prefix ´\epsilon´ are called direct designators.
They refer to local definitions available in the scope:

  • Local type, object, val, lazy val, var or def definitions
  • Term or type parameters

The ids of direct designators are protected from accidental shadowing in the abstract syntax.
They retain the identity of the exact definition they refer to, rather than relying on scope-based name resolution. [^debruijnoralpha]

[^debruijnoralpha]: In the literature, this is often achieved through De Bruijn indices or through alpha-renaming when needed. In a concrete implementation, this is often achieved through retaining symbolic references in a symbol table.

The ´\epsilon´ prefix cannot be written in the concrete syntax.
A bare id is used instead and resolved based on scopes.

Named designators refer to member definitions of a non-empty prefix:

  • Top-level definitions, including top-level classes, have a package ref prefix
  • Class member definitions and refinements have a type prefix

Term Designators

A term designator ´p.x´ referring to a term definition t has an underlying type ´U´.
If ´p = \epsilon´ or ´p´ is a package ref, the underlying type ´U´ is the declared type of t and ´p.x´ is a stable type if an only if t is a val or object definition.
Otherwise, the underlying type ´U´ and whether ´p.x´ is a stable type are determined by memberType(´p´, ´x´).

All term designators are concrete types.
If scala.Null ´<: U´, the term designator denotes the set of values consisting of null and the value denoted by ´t´, i.e., the value ´v´ for which t eq v.
Otherwise, the designator denotes the singleton set only containing ´v´.

Type Designators

A type designator ´p.C´ referring to a class definition (including traits and hidden object classes) is a class type.
If the class is monomorphic, the type designator is a value type denoting the set of instances of ´C´ or any of its subclasses.
Otherwise it is a type constructor with the same type parameters as the class definition.
All class types are concrete, non-stable types.

If a type designator ´p.T´ is not a class type, it refers to a type definition T (a type parameter or a type member definition) and has an underlying type definition.
If ´p = \epsilon´ or ´p´ is a package ref, the underlying type definition is the declared type definition of T.
Otherwise, it is determined by memberType(´p´, ´T´).
A non-class type designator is concrete (resp. stable) if and only if its underlying type definition is an alias ´U´ and ´U´ is itself concrete (resp. stable).

Parameterized Types

ebnf
ParameterizedType ::=  Type ‘[‘ TypeArgs ‘]‘
TypeArgs          ::=  TypeArg {‘,‘ TypeArg}
TypeArg           ::=  Type
                    |  WilcardTypeArg
WildcardTypeArg   ::=  ‘?‘ TypeBounds

A parameterized type ´T[T_1, ..., T_n]´ consists of a type constructor ´T´ and type arguments ´T_1, ..., T_n´ where ´n \geq 1´.
The parameterized type is well-formed if

  • ´T´ is a type constructor which takes ´n´ type parameters ´a_1, ..., a_n´, i.e., it must conform to a type lambda of the form ´[\pm a_1 >: L_1 <: H_1, ..., \pm a_n >: L_n <: H_n] => U´, and
  • if ´T´ is an abstract type constructor, none of the type arguments is a wildcard type argument, and
  • each type argument conforms to its bounds, i.e., given ´\sigma´ the substitution ´[a_1 := T_1, ..., a_n := T_n]´, for each type ´i´:
    • if ´T_i´ is a type and ´\sigma L_i <: T_i <: \sigma H_i´, or
    • ´T_i´ is a wildcard type argument ´? >: L_{Ti} <: H_{Ti}´ and ´\sigma L_i <: L_{Ti}´ and ´H_{Ti} <: \sigma H_i´.

´T[T_1, ..., T_n]´ is a parameterized class type if and only if ´T´ is a class type.
All parameterized class types are value types.

In the concrete syntax of wildcard type arguments, if both bounds are omitted, the real bounds are inferred from the bounds of the corresponding type parameter in the target type constructor (which must be concrete).
If only one bound is omitted, Nothing or Any is used, as usual.

Also in the concrete syntax, _ can be used instead of ? for compatibility reasons, with the same meaning.
This alternative will be deprecated in the future, and is already deprecated under -source:future.

Simplification Rules

Wildcard type arguments used in covariant or contravariant positions can always be simplified to regular types.

Let ´T[T_1, ..., T_n]´ be a parameterized type for a concrete type constructor.
Then, applying a wildcard type argument ´? >: L <: H´ at the ´i´'th position obeys the following equivalences:

  • If the type parameter ´T_i´ is declared covariant, then ´T[..., ? >: L <: H, ...] =:= T[..., H, ...]´.
  • If the type parameter ´T_i´ is declared contravariant, then ´T[..., ? >: L <: H, ...] =:= T[..., L, ...]´.

Example Parameterized Types

Given the partial type definitions:

scala
class TreeMap[A <: Comparable[A], B] { ... }
class List[+A] { ... }
class I extends Comparable[I] { ... }

class F[M[A], X] { ... } // M[A] desugars to M <: [A] =>> Any
class S[K <: String] { ... }
class G[M[Z <: I], I] { ... } // M[Z <: I] desugars to M <: [Z <: I] =>> Any

the following parameterized types are well-formed:

scala
TreeMap[I, String]
List[I]
List[List[Boolean]]

F[List, Int]
F[[X] =>> List[X], Int]
G[S, String]

List[?] // ? inferred as List[_ >: Nothing <: Any], equivalent to List[Any]
List[? <: String] // equivalent to List[String]
S[? <: String]
F[?, Boolean] // ? inferred as ? >: Nothing <: [A] =>> Any

and the following types are ill-formed:

scala
TreeMap[I]            // illegal: wrong number of parameters
TreeMap[List[I], Int] // illegal: type parameter not within bound
List[[X] => List[X]]

F[Int, Boolean]       // illegal: Int is not a type constructor
F[TreeMap, Int]       // illegal: TreeMap takes two parameters,
                      //   F expects a constructor taking one
F[[X, Y] => (X, Y)]
G[S, Int]             // illegal: S constrains its parameter to
                      //   conform to String,
                      // G expects type constructor with a parameter
                      //   that conforms to Int

The following code also contains an ill-formed type:

scala
trait H[F[A]]:  // F[A] desugars to F <: [A] =>> Any, which is abstract
  def f: F[_]   // illegal : an abstract type constructor
                // cannot be applied to wildcard arguments.

This Types

ebnf
ThisType  ::=  classid ‘.‘ ‘this‘

A this type ´C´.this denotes the this value of class ´C´ within ´C´.

This types often appear implicitly as the prefix of designator types referring to members of ´C´.
They play a particular role in the type system, since they are affected by the as seen from operation on types.

This types are stable types.
The underlying type of ´C´.this is the self type of ´C´.

Super Types

ebnf
SuperType  ::=  classid ‘.‘ ‘super‘ ‘[‘ classid ‘]‘

A super type ´C´.super[´D´] denotes the this value of class C within C, but "widened" to only see members coming from a parent class or trait ´D´.

Super types exist for compatibility with Scala 2, which allows shadowing of inner classes.
In a Scala 3-only context, a super type can always be replaced by the corresponding this type.
Therefore, we omit further discussion of super types in this specification.

Literal Types

ebnf
LiteralType  ::=  SimpleLiteral

A literal type lit denotes the single literal value lit.
Thus, the type ascription 1: 1 gives the most precise type to the literal value 1: the literal type 1.

At run time, an expression e is considered to have literal type lit if e == lit.
Concretely, the result of e.isInstanceOf[lit] and e match { case _ : lit => } is determined by evaluating e == lit.

Literal types are available for all primitive types, as well as for String.
However, only literal types for Int, Long, Float, Double, Boolean, Char and String can be expressed in the concrete syntax.

Literal types are stable types.
Their underlying type is the primitive type containing their value.

Example

scala
val x: 1 = 1
val y: false = false
val z: false = y
val int: Int = x

val badX: 1 = int       // error: Int is not a subtype of 1
val badY: false = true  // error: true is not a subtype of false

By-Name Types

ebnf
ByNameType  ::=  ‘=>‘ Type

A by-name type ´=> T´ denotes the declared type of a by-name term parameter.
By-name types can only appear as the types of parameters in method types, and as type arguments in parameterized types.

Annotated Types

ebnf
AnnotatedType  ::=  Type Annotation

An annotated type ´T a´ attaches the annotation ´a´ to the type ´T´.

Example

The following type adds the @suspendable annotation to the type String:

scala
String @suspendable

Refined Types

ebnf
RefinedType  ::=  Type ‘{‘ Refinement ‘}‘
Refinement   ::=  ‘type‘ id TypeAliasOrBounds
               |  ‘def‘ id ‘:‘ TypeOrMethodic
               |  ‘val‘ id ‘:‘ Type

A refined type ´T { R }´ denotes the set of values that belong to ´T´ and also have a member conforming to the refinement ´R´.

The refined type ´T { R }´ is well-formed if:

  • ´T´ is a proper type, and
  • if ´R´ is a term (def or val) refinement, the refined type is a proper type, and
  • if ´R´ overrides a member of ´T´, the usual rules for overriding apply, and
  • if ´R´ is a def refinement with a polymorphic method type, then ´R´ overrides a member definition of ´T´.

As an exception to the last rule, a polymorphic method type refinement is allowed if ´T <:´ scala.PolyFunction and ´id´ is the name apply.

If the refinement ´R´ overrides no member of ´T´ and is not an occurrence of the scala.PolyFunction exception, the refinement is said to be “structural” [^2].

[^2]: A reference to a structurally defined member (method call or access to a value or variable) may generate binary code that is significantly slower than an equivalent code to a non-structural member.

Note: since a refinement does not define a class, it is not possible to use a this type to reference term and type members of the parent type ´T´ within the refinement.
When the surface syntax of refined types makes such references, a recursive type wraps the refined type, given access to members of self through a recursive-this type.

Example

Given the following class definitions:

scala
trait T:
  type X <: Option[Any]
  def foo: Any
  def fooPoly[A](x: A): Any

trait U extends T:
  override def foo: Int
  override def fooPoly[A](x: A): A

trait V extends T
  type X = Some[Int]
  def bar: Int
  def barPoly[A](x: A): A

We get the following conformance relationships:

  • U <: T { def foo: Int }
  • U <: T { def fooPoly[A](x: A): A }
  • U <: (T { def foo: Int }) { def fooPoly[A](x: A): A } (we can chain refined types to refine multiple members)
  • V <: T { type X <: Some[Any] }
  • V <: T { type X >: Some[Nothing] }
  • V <: T { type X = Some[Int] }
  • V <: T { def bar: Any } (a structural refinement)

The following refined types are not well-formed:

  • T { def barPoly[A](x: A): A } (structural refinement for a polymorphic method type)
  • T { type X <: List[Any] } (does not satisfy overriding rules)
  • List { def head: Int } (the parent type List is not a proper type)
  • T { def foo: List } (the refined type List is not a proper type)
  • T { def foo: T.this.X } (T.this is not allowed outside the body of T)

Recursive Types

ebnf
RecursiveType  ::=  ‘{‘ recid ‘=>‘ Type ‘}‘
RecursiveThis  ::=  recid ‘.‘ ‘this‘

A recursive type of the form { ´\alpha´ => ´T´ } represents the same values as ´T´, while offering ´T´ access to its recursive this type ´\alpha´.

Recursive types cannot directly be expressed in the concrete syntax.
They are created as needed when a refined type in the concrete syntax contains a refinement that needs access to the this value.
Each recursive type defines a unique self-reference ´\alpha´, distinct from any other recursive type in the system.

Recursive types can be unfolded during subtyping as needed, replacing references to its ´\alpha´ by a stable reference to the other side of the conformance relationship.

Example

Given the class definitions in the refined types section, we can write the following refined type in the source syntax:

scala
T { def foo: X }
// equivalent to
T { def foo: this.X }

This type is not directly expressible as a refined type alone, as the refinement cannot access the this value.
Instead, in the abstract syntax of types, it is translated to { ´\alpha´ => ´T´ { def foo: ´\alpha´.X } }.

Given the following definitions:

scala
trait Z extends T:
  type X = Option[Int]
  def foo: Option[Int] = Some(5)

val z: Z

we can check that z ´<:´ { ´\alpha´ => ´T´ { def foo: ´\alpha´.X } }.
We first unfold the recursive type, substituting ´z´ for ´\alpha´, resulting in z ´<:´ T { def foo: z.X }.
Since the underlying type of ´z´ is ´Z´, we can resolve z.X to mean Option[Int], and then validate that z ´<:´ T and that z has a member def foo: Option[Int].

Union and Intersection Types

ebnf
UnionType         ::=  Type ‘|‘ Type
IntersectionType  ::=  Type ‘&‘ Type

Syntactically, the types S | T and S & T are infix types, where the infix operators are | and &, respectively (see infix types).

However, in this specification, ´S | T´ and ´S & T´ refer to the underlying core concepts of union and intersection types, respectively.

  • The type ´S | T´ represents the set of values that are represented by either ´S´ or ´T´.
  • The type ´S & T´ represents the set of values that are represented by both ´S´ and ´T´.

From the conformance rules rules on union and intersection types, we can show that ´&´ and ´|´ are commutative and associative.
Moreover, & is distributive over |.
For any type ´A´, ´B´ and ´C´, all of the following relationships hold:

  • ´A & B =:= B & A´,
  • ´A | B =:= B | A´,
  • ´(A & B) & C =:= A & (B & C)´,
  • ´(A | B) | C =:= A | (B | C)´, and
  • ´A & (B | C) =:= (A & B) | (A & C)´.

If ´C´ is a co- or contravariant type constructor, ´C[A] & C[B]´ can be simplified using the following rules:

  • If ´C´ is covariant, ´C[A] & C[B] =:= C[A & B]´
  • If ´C´ is contravariant, ´C[A] & C[B] =:= C[A | B]´

The right-to-left validity of the above two rules can be derived from the definition of covariance and contravariance and the conformance rules of union and intersection types:

  • When ´C´ is covariant, we can derive ´C[A & B] <: C[A] & C[B]´.
  • When ´C´ is contravariant, we can derive ´C[A | B] <: C[A] & C[B]´.

Join of a union type

In some situations, a union type might need to be widened to a non-union type.
For this purpose, we define the join of a union type ´T_1 | ... | T_n´ as the smallest intersection type of base class instances of ´T_1, ..., T_n´.
Note that union types might still appear as type arguments in the resulting type, this guarantees that the join is always finite.

For example, given

scala
trait C[+T]
trait D
trait E
class A extends C[A] with D
class B extends C[B] with D with E

The join of ´A | B´ is ´C[A | B] & D´

Match Types

ebnf
MatchType               ::=  Type ‘match‘ ‘<:‘ Type ‘{‘ {TypeCaseClause} ‘}‘
TypeCaseClause          ::=  ‘case‘ TypeCasePattern ‘=>‘ Type
TypeCasePattern         ::=  TypeCapture
                          |  TypeCaseAppliedPattern
                          |  Type
TypeCaseAppliedPattern  ::=  Type ‘[‘ TypeCasePattern { ‘,‘ TypeCasePattern } ‘]‘
TypeCapture             ::=  (id | ‘_‘) TypeBounds

A match type contains a scrutinee, a list of case clauses, and an upper bound.
The scrutinee and the upper bound must both be proper types.
A match type can be reduced to the body of a case clause if the scrutinee matches its pattern, and if it is provably disjoint from every earlier pattern.

A TypeCasePattern is a legal pattern if and only if one of the following is true:

  • It is a Type, or
  • It is a TypeCaseAppliedPattern of the form ´P´[´P_1´, ..., ´P_n´] where ´P´ is a "pattern-legal type constructor" and for each ´i´, either:
    • ´P_i´ is a TypeCapture, or
    • ´P_i´ is a Type, or
    • ´P_i´ is a TypeCaseAppliedPattern, the type constructor ´P´ is covariant in its ´i´th type parameter, and ´P_i´ is recursively a legal pattern.

A type ´P´ is a "pattern-legal type constructor" if one of the following is true:

  • It is a class type constructor, or
  • It is the scala.compiletime.ops.int.S type constructor, or
  • It is an abstract type constructor, or
  • It is a type lambda with a refined result type of the form [´a´ >: ´L´ <: ´H´] =>> ´B´ { type ´T´ = ´a´ } where:
    • ´B´ contains no occurrence of ´a´,
    • there exists a type member ´T´ in ´B´, and
    • the bounds >: ´L´ <: ´H´ are not any more restrictive than those of ´T´ in ´B´, i.e., ´L´ <: ´(∃ \alpha : B).T´ <: ´H´.
  • It is a type lambda of the form [´\pm a_1 >: L_1 <: H_1´, ..., ´\pm a_n >: L_n <: H_n´] =>> ´U´ such that:
    • Its bounds contain all possible values of its arguments, and
    • When applied to the type arguments, it beta-reduces to a new legal MatchTypeAppliedPattern that contains exactly one instance of every type capture present in the type arguments.
  • It is a concrete type designator with underlying type definition = ´U´ and ´U´ is recursively a "pattern-legal type constructor".

Given the following definitions:

scala
class Inv[A]
class Cov[+A]
class Contra[-A]

class Base {
  type Y
}

type YExtractor[t] = Base { type Y = t }
type ZExtractor[t] = Base { type Z = t }

type IsSeq[t <: Seq[Any]] = t

Here are examples of legal patterns:

scala
// TypeWithoutCapture's
case Any => // also the desugaring of `case _ =>` when the _ is at the top-level
case Int =>
case List[Int] =>
case Array[String] =>

// Class type constructors with direct captures
case scala.collection.immutable.List[t] => // not Predef.List; it is a type alias
case Array[t] =>
case Contra[t] =>
case Either[s, t] =>
case Either[s, Contra[Int]] =>
case h *: t =>
case Int *: t =>

// The S type constructor
case S[n] =>

// An abstract type constructor
// given a [F[_]] or `type F[_] >: L <: H` in scope
case F[t] =>

// Nested captures in covariant position
case Cov[Inv[t]] =>
case Cov[Cov[t]] =>
case Cov[Contra[t]] =>
case Array[h] *: t => // sugar for *:[Array[h], t]
case g *: h *: EmptyTuple =>

// Type aliases
case List[t] => // which is Predef.List, itself defined as `type List[+A] = scala.collection.immutable.List[A]`

// Refinements (through a type alias)
case YExtractor[t] =>

The following patterns are not legal:

scala
// Type capture nested two levels below a non-covariant type constructor
case Inv[Cov[t]] =>
case Inv[Inv[t]] =>
case Contra[Cov[t]] =>

// Type constructor with bounds that do not contain all possible instantiations
case IsSeq[t] =>

// Type refinement where the refined type member is not a member of the parent
case ZExtractor[t] =>

Matching

Given a scrutinee X and a match type case case P => R with type captures ts, matching proceeds in three steps:

  1. Compute instantiations for the type captures ts', and check that they are specific enough.
  2. If successful, check that X <:< [ts := ts']P.
  3. If successful, reduce to [ts := ts']R.

The instantiations are computed by the recursive function matchPattern(X, P, variance, scrutIsWidenedAbstract).
At the top level, variance = 1 and scrutIsWidenedAbstract = false.

matchPattern behaves according to what kind is P:

  • If P is a TypeWithoutCapture:
    • Do nothing (always succeed).
  • If P is a WildcardCapture ti = _:
    • If X is of the form _ >: L <: H, instantiate ti := H (anything between L and H would work here),
    • Otherwise, instantiate ti := X.
  • If P is a TypeCapture ti:
    • If X is of the form _ >: L <: H,
      • If scrutIsWidenedAbstract is true, fail as not specific.
      • Otherwise, if variance = 1, instantiate ti := H.
      • Otherwise, if variance = -1, instantiate ti := L.
      • Otherwise, fail as not specific.
    • Otherwise, if variance = 0 or scrutIsWidenedAbstract is false, instantiate ti := X.
    • Otherwise, fail as not specific.
  • If P is a MatchTypeAppliedPattern of the form T[Qs]:
    • Assert: variance = 1 (from the definition of legal patterns).
    • If T is a class type constructor of the form p.C:
      • If baseType(X, C) is not defined, fail as not matching.
      • Otherwise, it is of the form q.C[Us].
      • If p =:= q is false, fail as not matching.
      • Let innerScrutIsWidenedAbstract be true if either scrutIsWidenedAbstract or X is not a concrete type.
      • For each pair of (Ui, Qi), compute matchPattern(Ui, Qi, vi, innerScrutIsWidenedAbstract) where vi is the variance of the ith type parameter of T.
    • If T is scala.compiletime.ops.int.S:
      • If n = natValue(X) is undefined or n <= 0, fail as not matching.
      • Otherwise, compute matchPattern(n - 1, Q1, 1, scrutIsWidenedAbstract).
    • If T is an abstract type constructor:
      • If X is not of the form F[Us] or F =:= T is false, fail as not matching.
      • Otherwise, for each pair of (Ui, Qi), compute matchPattern(Ui, Qi, vi, scrutIsWidenedAbstract) where vi is the variance of the ith type parameter of T.
    • If T is a refined type of the form Base { type Y = ti }:
      • Let q be X if X is a stable type, or the skolem type ∃α:X otherwise.
      • If q does not have a type member Y, fail as not matching (that implies that X <:< Base is false, because Base must have a type member Y for the pattern to be legal).
      • If q is not a skolem type:
        • Compute matchPattern(ti, q.Y, 0, scrutIsWidenedAbstract).
      • Otherwise, if q.Y is a type alias with underlying type definition = U:
        • Let U' be the result of perform type avoidance on U to remove references to q.
        • If successful, compute matchPattern(ti, U', 0, scrutIsWidenedAbstract).
        • Otherwise, fail as not specific.
    • If T is a concrete type alias to a type lambda:
      • Let P' be the beta-reduction of P.
      • Compute matchPattern(P', X, variance, scrutIsWidenedAbstract).

Disjointness

A scrutinee ´X´ is provably disjoint from a pattern ´P´ iff it is provably disjoint from the type ´P'´ obtained by replacing every type capture in ´P´ by a wildcard type argument with the same bounds.

We note ´X ⋔ Y´ to say that ´X´ and ´Y´ are provably disjoint.
Intuitively, that notion is based on the following properties of the Scala language:

  • Single inheritance of classes
  • Final classes cannot be extended
  • Sealed traits have a known set of direct children
  • Constant types with distinct values are nonintersecting
  • Singleton paths to distinct enum case values are nonintersecting

However, a precise definition of provably-disjoint is complicated and requires some helpers.
We start with the notion of "simple types", which are a minimal subset of Scala internal types that capture the concepts mentioned above.

A "simple type" is one of:

  • Nothing
  • AnyKind
  • ´p.C[...X_i]´ a possibly parameterized class type, where ´p´ and ´...X_i´ are arbitrary types (not just simple types)
  • ´c´ a literal type
  • ´p.C.x´ where C is an enum class and x is one of its value cases
  • ´X_1 & X_2´ where ´X_1´ and ´X_2´ are both simple types
  • ´X_1 | X_2´ where ´X_1´ and ´X_2´ are both simple types
  • ´[...a_i]´ =>> ´X_1´ where ´X_1´ is a simple type

We define ´⌈X⌉´ a function from a full Scala type to a simple type.
Intuitively, it returns the "smallest" simple type that is a supertype of X.
It is defined as follows:

  • ´⌈X⌉ = X´ if ´X´ is a simple type
  • ´⌈X⌉ = ⌈U⌉´ if ´X´ is a stable type but not a simple type and its underlying type is ´U´
  • ´⌈X⌉ = ⌈H⌉´ if ´X´ is a non-class type designator with upper bound ´H´
  • ´⌈X⌉ = ⌈η(X)⌉´ if ´X´ is a polymorphic class type designator, where ´η(X)´ is its eta-expansion
  • ´⌈X⌉ = ⌈Y⌉´ if ´X´ is a match type that reduces to ´Y´
  • ´⌈X⌉ = ⌈H⌉´ if ´X´ is a match type that does not reduce and ´H´ is its upper bound
  • ´⌈X[...T_i]⌉ = ⌈Y⌉´ where Y is the beta-reduction of ´X[...T_i]´ if ´X´ is a type lambda
  • ´⌈X[...T_i]⌉ = ⌈⌈X⌉[...T_i]⌉´ if ´X´ is neither a type lambda nor a class type designator
  • ´⌈X @a⌉ = ⌈X⌉´
  • ´⌈X´ { ´R´ }´⌉ = ⌈X⌉´
  • ´⌈´{ ´α´ => ´X´ }´ = ⌈X⌉⌉´
  • ´⌈X_1 & X_2⌉ = ⌈X_1⌉ & ⌈X_2⌉´
  • ´⌈X_1 | X_2⌉ = ⌈X_1⌉ | ⌈X_2⌉´
  • ´⌈[...a_i]´ =>> ´X_1⌉ = [...a_i]´ =>> ´⌈X_1⌉´

The following properties hold about ´⌈X⌉´ (we have paper proofs for those):

  • ´X <: ⌈X⌉´ for all type ´X´.
  • If ´S <: T´, and the subtyping derivation does not use the "lower-bound rule" of ´<:´ anywhere, then ´⌈S⌉ <: ⌈T⌉´.

The "lower-bound rule" states that ´S <: T´ if ´T = q.X´ and ´q.X´ is a non-class type designator and ´S <: L´ where ´L´ is the lower bound of the underlying type definition of ´q.X´".
That rule is known to break transitivy of subtyping in Scala already.

Second, we define the relation ´⋔´ on classes (including traits, hidden classes of objects, and enum terms) as:

  • ´C ⋔ D´ if ´C ∉´ baseClasses´(D)´ and ´D´ is final
  • ´C ⋔ D´ if ´D ∉´ baseClasses´(C)´ and ´C´ is final
  • ´C ⋔ D´ if there exists classes ´C' ∈´ baseClasses´(C)´ and ´D' ∈´ baseClasses´(D)´ such that ´C' ∉´ baseClasses´(D')´ and ´D' ∉´ baseClasses´(C')´.
  • ´C ⋔ D´ if ´C´ is sealed without anonymous child and ´C_i ⋔ D´ for all direct children ´C_i´ of ´C´
  • ´C ⋔ D´ if ´D´ is sealed without anonymous child and ´C ⋔ D_i´ for all direct children ´D_i´ of ´D´

We can now define ´⋔´ for types.

For arbitrary types ´X´ and ´Y´, we define ´X ⋔ Y´ as ´⌈X⌉ ⋔ ⌈Y⌉´.

Two simple types ´S´ and ´T´ are provably disjoint if there is a finite derivation tree for ´S ⋔ T´ using the following rules.
Most rules go by pair, which makes the whole relation symmetric:

  • Nothing is disjoint from everything (including itself):
    • Nothing ´⋔ T´
    • ´S ⋔´ Nothing
  • A union type is disjoint from another type if both of its parts are disjoint from that type:
    • ´S ⋔ T_1 | T_2´ if ´S ⋔ T_1´ and ´S ⋔ T_2´
    • ´S_1 | S_2 ⋔ T´ if ´S_1 ⋔ T´ and ´S_2 ⋔ T´
  • An intersection type is disjoint from another type if at least one of its parts is disjoint from that type:
    • ´S ⋔ T_1 & T_2´ if ´S ⋔ T_1´ or ´S ⋔ T_2´
    • ´S_1 & S_2 ⋔ T´ if ´S_1 ⋔ T´ or ´S_1 ⋔ T´
  • A type lambda is disjoint from any other type that is not a type lambda with the same number of parameters:
    • ´[...a_i]´ =>> ´S_1 ⋔ q.D.y´
    • ´[...a_i]´ =>> ´S_1 ⋔ d´
    • ´[...a_i]´ =>> ´S_1 ⋔ q.D[...T_i]´
    • ´p.C.x ⋔ [...b_i]´ =>> ´T_1´
    • ´c ⋔ [...b_i]´ =>> ´T_1´
    • ´p.C[...S_i] ⋔ [...b_i]´ =>> ´T_1´
    • ´[a_1, ..., a_n]´ =>> ´S_1 ⋔ [b_1, ..., b_m]´ =>> ´T_1´ if ´m \neq n´
  • Two type lambdas with the same number of type parameters are disjoint if their result types are disjoint:
    • ´[a_1, ..., a_n]´ =>> ´S_1 ⋔ [b_1, ..., b_n]´ =>> ´T_1´ if ´S_1 ⋔ T_1´
  • An enum value case is disjoint from any other enum value case (identified by either not being in the same enum class, or having a different name):
    • ´p.C.x ⋔ q.D.y´ if ´C \neq D´ or ´x \neq y´
  • Two literal types are disjoint if they are different:
    • ´c ⋔ d´ if ´c \neq d´
  • An enum value case is always disjoint from a literal type:
    • ´c ⋔ q.D.y´
    • ´p.C.x ⋔ d´
  • An enum value case or a constant is disjoint from a class type if it does not extend that class (because it's essentially final):
    • ´p.C.x ⋔ q.D[...T_i]´ if baseType´(p.C.x, D)´ is not defined
    • ´p.C[...S_i] ⋔ q.D.y´ if baseType´(q.D.y, C)´ is not defined
    • ´c ⋔ q.D[...T_i]´ if baseType´(c, D)´ is not defined
    • ´p.C[...S_i] ⋔ d´ if baseType´(d, C)´ is not defined
  • Two class types are disjoint if the classes themselves are disjoint, or if there exists a common super type with conflicting type arguments.
    • ´p.C[...S_i] ⋔ q.D[...T_i]´ if ´C ⋔ D´
    • ´p.C[...S_i] ⋔ q.D[...T_i]´ if there exists a class ´E´ such that baseType´(p.C[...S_i], E) = a.E[...A_i]´ and baseType´(q.D[...T_i], E) = b.E[...B_i]´ and there exists a pair ´(A_i, B_i)´ such that
      • ´A_i ⋔ B_i´ and it is in covariant position and there exists a field of that type parameter in ´E´, or
      • ´A_i ⋔ B_i´ and it is in invariant position, and:
        • there exists a field of that type parameter in ´E´, or
        • ´A_i´ cannot be instantiated to Nothing, or
        • ´B_i´ cannot be instantiated to Nothing.

It is worth noting that this definition disregards prefixes entirely.
´p.C´ and ´q.C´ are never provably disjoint, even if ´p´ could be proven disjoint from ´q´.
It also disregards type members.

We have a proof sketch of the following property for ´⋔´:

  • If ´S <: T´ and ´T ⋔ U´, then ´S ⋔ U´.

This is a very desirable property.
It means that if we make the scrutinee of a match type more precise (a subtype) through substitution, and the match type previously reduced, then the match type will still reduce to the same case.

Note: if ´⋔´ were a "true" disjointness relationship, and not a provably-disjoint relationship, that property would trivially hold based on elementary set theoretic properties.
It would amount to proving that if ´S ⊆ T´ and ´T ⋂ U = ∅´, then ´S ⋂ U = ∅´.

Reduction

The result of reducing ´X´ match { case ´P_1´ => ´R_1; ...;´ case ´P_n´ => ´R_n´ } can be a type, undefined, or a compile error.

For ´n \geq 1´, it is specified as:

  • If ´X´ matches ´P_1´ with type capture instantiations ´[...t_i \to t_i']´:
    • If ´X ⋔ P_1´, do not reduce.
    • Otherwise, reduce as ´[...t_i \to t_i']R_1´.
  • Otherwise,
    • If ´X ⋔ P1´, the result of reducing ´X´ match { case ´P_2´ => ´R_2; ...;´ case ´P_n´ => ´R_n´ } (i.e., proceed with subsequent cases).
    • Otherwise, do not reduce.

The reduction of an "empty" match type ´X´ match { } (which cannot be written in user programs) is a compile error.

Skolem Types

ebnf
SkolemType  ::=  ‘∃‘ skolemid ‘:‘ Type

Skolem types cannot directly be written in the concrete syntax.
Moreover, although they are proper types, they can never be inferred to be part of the types of term definitions (vals, vars and defs).
They are exclusively used temporarily during subtyping derivations.

Skolem types are stable types.
A skolem type of the form ´∃ \alpha : T´ represents a stable reference to unknown value of type ´T´.
The identifier ´\alpha´ is chosen uniquely every time a skolem type is created.
However, as a skolem type is stable, it can be substituted in several occurrences in other types.
When "copied" through substitution, all the copies retain the same ´\alpha´, and are therefore equivalent.

Methodic Types

ebnf
TypeOrMethodic    ::=  Type
                    |  MethodicType
MethodicType      ::=  MethodType
                    |  PolyType

Methodic types are not real types.
They are not part of the type lattice.

However, they share some meta-properties with types.
In particular, when contained within other types that undertake some substitution, the substitution carries to the types within methodic types.
It is therefore often convenient to think about them as types themselves.

Methodic types are used as the "declared type" of def definitions that have at least one term or type parameter list.

Method Types

ebnf
MethodType        ::=  ‘(‘ MethodTypeParams ‘)‘ TypeOrMethodic
MethodTypeParams  ::=  ε
                    |  MethodTypeParam {‘,‘ MethodTypeParam}
MethodTypeParam   ::=  id ‘:‘ Type

A method type is denoted internally as ´(\mathit{Ps})U´, where ´(\mathit{Ps})´ is a sequence of parameter names and types ´(p_1:T_1, ..., p_n:T_n)´ for some ´n \geq 0´ and ´U´ is a (value or method) type.
This type represents named methods that take arguments named ´p_1, ..., p_n´ of types ´T_1, ..., T_n´ and that return a result of type ´U´.

Method types associate to the right: ´(\mathit{Ps}_1)(\mathit{Ps}_2)U´ is treated as ´(\mathit{Ps}_1)((\mathit{Ps}_2)U)´.

Method types do not exist as types of values.
If a method name is used as a value, its type is implicitly converted to a corresponding function type.

Example

The definitions

scala
def a: Int
def b (x: Int): Boolean
def c (x: Int) (y: String, z: String): String

produce the typings

scala
a: Int
b: (Int) Boolean
c: (Int) (String, String) String

Polymorphic Method Types

ebnf
PolyType          ::=  ‘[‘ PolyTypeParams ‘]‘ TypeOrMethodic
PolyTypeParams    ::=  PolyTypeParam {‘,‘ PolyTypeParam}
PolyTypeParam     ::=  ‘id‘ TypeBounds

A polymorphic method type, or poly type for short, is denoted internally as [´\mathit{tps}\,´]´T´ where [´\mathit{tps}\,´] is a type parameter section [´a_1´ >: ´L_1´ <: ´U_1, ..., a_n´ >: ´L_n´ <: ´U_n´] for some ´n \geq 0´ and ´T´ is a (value or method) type.
This type represents named methods that take type arguments ´S_1, ..., S_n´ which conform to the lower bounds ´L_1, ..., L_n´ and the upper bounds ´U_1, ..., U_n´ and that yield results of type ´T´.

Example

The definitions

scala
def empty[A]: List[A]
def union[A <: Comparable[A]] (x: Set[A], xs: Set[A]): Set[A]

produce the typings

scala
empty : [A >: Nothing <: Any] List[A]
union : [A >: Nothing <: Comparable[A]] (x: Set[A], xs: Set[A]) Set[A]

Operations on Types

This section defines a few meta-functions on types and methodic types.

These meta-functions are mutually recursive.

Base Type

The meta-function baseType(´T´, ´C´), where ´T´ is a proper type and ´C´ is a class identifier, computes the smallest type ´U´ of the form ´p.C´ or ´p.C´[´U_1, ..., U_n´] such that ´T <: U´.
If no such type exists, the function is not defined.
The main purpose of baseType is to substitute prefixes and class type parameters along the inheritance chain.

We define baseType(´T´, ´C´) as follows.
For brevity, we write ´p.X´[´U_1, ..., U_n´] instead of ´p.X´ with ´n = 0´.

  • baseType(´T = p.C´[´T_1, ..., T_n´], ´C´) ´≜ T´
  • baseType(´p.D´[´T_1, ..., T_n´], ´C´) with ´D´ ≠ ´C ≜ \sigma W´ if ´Q´ is defined where
    • ´D´ is declared as ´D[\pm a_1 >: L_1 <: H_1, ..., \pm a_n >: L_n <: H_n]´ extends ´P_1, ..., P_m´
    • ´Q =´ meet(baseType(´P_i´, ´C´) for all ´i´ such that baseType(´P_i´, ´C´) is defined)
    • ´W = Q´ if ´p = \epsilon´ or if ´p´ is a package ref; otherwise, ´W =´ asSeenFrom(´Q´, ´D´, ´p´) (in that case, ´p´ is a stable type and ´D´ must be declared inside another class ´B´)
    • ´\sigma = [a_1 := T_1, ..., a_n := T_n]´ the substitution of the declared type parameters of ´D´ by the actual type arguments
  • baseType(´T_1 & T_2´, ´C´) ´≜´ meet´(´baseType(´T_1´, ´C´), baseType(´T_2´, ´C´)´)´
  • baseType(´T_1 | T_2´, ´C´) ´≜´ join´(´baseType(´T_1´, ´C´), baseType(´T_2´, ´C´)´)´
  • baseType(´T´, ´C´) ´≜´ baseType(superType(´T´), ´C´) if superType(´T´) is defined

The definition above uses the following helper functions.

superType(´T´) computes the "next upper bound" of ´T´, if it exists:

  • superType(´T´) where ´T´ is a stable type is its underlying type
  • superType(´p.X´) where ´p.X´ is a non-class type designator is the upper bound of its underlying type definition
  • superType(´([a_1 >: L_1 <: H_1, ..., a_n >: L_n <: H_n]´ =>> ´U)[T_1, ..., T_n]´) is ´[a_1 =: T_1, ..., a_n := T_n]U´ (i.e., the beta-reduction of the type lambda redex)
  • superType(´T[T_1, ..., T_n]´) is superType(´T´)´[T_1, ..., T_n]´ if superType(´T´) is defined

Note that the cases of superType do not overlap with each other nor with any baseType case other than the superType-based one.
The cases of baseType therefore do not overlap with each other either.
That makes baseType an algorithmic partial function.

meet(´p.C[T_1, ..., T_n]´, ´q.C[U_1, ..., U_n]´) computes an intersection of two (parameterized) class types for the same class, and join computes a union:

  • if ´p =:= q´ is false, then it is not defined
  • otherwise, let ´W_i´ for ´i \in 1, ..., n´ be:
    • ´T_i & U_i´ for meet (resp. ´T_i | U_i´ for join) if the ´i´th type parameter of ´C´ is covariant
    • ´T_i | U_i´ for meet (resp. ´T_i & U_i´ for join) if the ´i´th type parameter of ´C´ is contravariant
    • ´T_i´ if ´T_i =:= U_i´ and the ´i´th type parameter of ´C´ is invariant
    • not defined otherwise
  • if any of the ´W_i´ are not defined, the result is not defined
  • otherwise, the result is ´p.C[W_1, ..., W_n]´

We generalize meet(´T_1, ..., T_n´) for a sequence as:

  • not defined for ´n = 0´
  • ´T_1´ if ´n = 1´
  • meet(meet(´T_1, ..., T_{n-1}´), ´T_n´) if meet(´T_1, ..., T_{n-1}´) is defined
  • not defined otherwise

Examples

Given the following definitions:

scala
trait Iterable[+A]
trait List[+A] extends Iterable[A]
trait Map[K, +V] extends Iterable[(K, V)]
trait Foo

we have the following baseType results:

  • baseType(List[Int], List) = List[Int]
  • baseType(List[Int], Iterable) = Iterable[Int]
  • baseType(List[A] & Iterable[B], Iterable) = meet(Iterable[A], Iterable[B]) = Iterable[A & B]
  • baseType(List[A] & Foo, Iterable) = Iterable[A] (because baseType(Foo, Iterable) is not defined)
  • baseType(Int, Iterable) is not defined
  • baseType(Map[Int, String], Iterable) = Iterable[(Int, String)]
  • baseType(Map[Int, String] & Map[String, String], Map) is not defined (because K is invariant)

As Seen From

The meta-function asSeenFrom(´T´, ´C´, ´p´), where ´T´ is a type or methodic type visible inside the class ´C´ and ´p´ is a stable type, rebases the type ´T´ "as seen from" the prefix ´p´.
Essentially, it substitutes this-types and class type parameters in ´T´ to appropriate types visible from outside.
Since T is visible inside ´C´, it can contain this-types and class type parameters of ´C´ itself as well as of all its enclosing classes.
This-types of enclosing classes must be mapped to appropriate subprefixes of ´p´, while class type parameters must be mapped to appropriate concrete type arguments.

asSeenFrom(´T´, ´C´, ´p´) only makes sense if ´p´ has a base type for ´C´, i.e., if baseType(´p´, ´C´) is defined.

We define asSeenFrom(´T´, ´C´, ´p´) where baseType(´p´, ´C´) = ´q.C[U_1, ..., U_n]´ as follows:

  • If ´T´ is a reference to the ´i´th class type parameter of some class ´D´:
    • If baseType(´p´, ´D´) ´= r.D[W_1, ..., W_m]´ is defined, then ´W_i´
    • Otherwise, if ´q = \epsilon´ or ´q´ is a package ref, then ´T´
    • Otherwise, ´q´ is a type, ´C´ must be defined in another class ´B´ and baseType(´q´, ´B´) must be defined, then asSeenFrom(´T´, ´B´, ´q´)
  • Otherwise, if ´T´ is a this-type ´D´.this:
    • If ´D´ is a subclass of ´C´ and baseType(´p´, ´D´) is defined, then ´p´ (this is always the case when ´D = C´)
    • Otherwise, if ´q = \epsilon´ or ´q´ is a package ref, then ´T´
    • Otherwise, ´q´ is a type, ´C´ must be defined in another class ´B´ and baseType(´q´, ´B´) must be defined, then asSeenFrom(´T´, ´B´, ´q´)
  • Otherwise, ´T´ where each if of its type components ´T_i´ is mapped to asSeenFrom(´T_i´, ´C´, ´p´).

For convenience, we generalize asSeenFrom to type definitions ´D´.

  • If ´D´ is an alias ´= U´, then asSeenFrom(´D´, ´C´, ´p´) = asSeenFrom(´U´, ´C´, ´p´).
  • If ´D´ is an abstract type definition with bounds ´>: L <: H´, then asSeenFrom(´D´, ´C´, ´p´) = ´>:´ asSeenFrom(´L´, ´C´, ´p´) ´<:´ asSeenFrom(´H´, ´C´, ´p´).

Member Type

The meta-function memberType(´T´, ´id´, ´p´), where ´T´ is a proper type, ´id´ is a term or type identifier, and ´p´ is a stable type, finds a member of a type (T.id) and computes its underlying type (for a term) or type definition (for a type) as seen from the prefix ´p´.
For a term, it also computes whether the term is stable.
memberType is the fundamental operation that computes the underlying type or underlying type definition of a named designator type.

The result ´M´ of a memberType is one of:

  • undefined,
  • a term result with underlying type or methodic type ´U´ and a stable flag,
  • a class result with class ´C´, or
  • a type result with underlying type definition ´D´.

As short-hand, we define memberType(´T´, ´id´) to be the same as memberType(´T´, ´id´, ´T´) when ´T´ is a stable type.

We define memberType(´T´, ´id´, ´p´) as follows:

  • If ´T´ is a possibly parameterized class type of the form ´q.C[T_1, ..., T_n]´ (with ´n \geq 0´):
    • Let ´m´ be the class member of ´C´ with name ´id´.
    • If ´m´ is not defined, the result is undefined.
    • If ´m´ is a class definition, the result is a class result with class ´m´.
    • If ´m´ is a term definition in class ´D´ with declared type ´U´, the result is a term result with underlying type asSeenFrom(´U´, ´D´, ´p´) and stable flag true if and only if ´m´ is stable.
    • If ´m´ is a type member definition in class ´D´, the result is a type result with underlying type definition asSeenFrom(´U´, ´D´, ´p´) where ´U´ is defined as follows:
      • If ´m´ is an opaque type alias member definition with declared definition ´>: L <: H = V´, then
        • ´U´ is ´= V´ if ´p = D.´this or if we are computing memberType in a transparent mode,
        • ´U´ is ´>: L <: H´ otherwise.
      • ´U´ is the declared type definition of ´m´ otherwise.
  • If ´T´ is another monomorphic type designator of the form ´q.X´:
    • Let ´U´ be memberType(´q´, ´X´)
    • Let ´H´ be the upper bound of ´U´
    • The result is memberType(´H´, ´id´, ´p´)
  • If ´T´ is another parameterized type designator of the form ´q.X[T_1, ..., T_n]´ (with ´n \geq 0´):
    • Let ´U´ be memberType(´q´, ´X´)
    • Let ´H´ be the upper bound of ´U´
    • The result is memberType(´H[T_1, ..., T_n]´, ´id´, ´p´)
  • If ´T´ is a parameterized type lambda of the form ´([\pm a_1 >: L_1 <: H_1, ..., \pm a_n >: L_n <: H_n]´ =>> ´U)[T_1, ..., T_n]´:
    • The result is memberType(´[a_1 := T_1, ..., a_n := T_n] U´, ´id´, ´p´), i.e., we beta-reduce the type redex.
  • If ´T´ is a refined type of the form ´T_1´ { ´R´ }:
    • Let ´M_1´ be the result of memberType(´T_1´, ´id´, ´p´).
    • If the name of the refinement ´R´ is not ´id´, let ´M_2´ be undefined.
    • Otherwise, let ´M_2´ be the type or type definition of the refinement ´R´, as well as whether it is stable.
    • The result is mergeMemberType(´M_1´, ´M_2´).
  • If ´T´ is a union type of the form ´T_1 | T_2´:
    • Let ´J´ be the join of ´T´.
    • The result is memberType(´J´, ´id´, ´p´).
  • If ´T´ is an intersection type of the form ´T_1 & T_2´:
    • Let ´M_1´ be the result of memberType(´T_1´, ´id´, ´p´).
    • Let ´M_2´ be the result of memberType(´T_2´, ´id´, ´p´).
    • The result is mergeMemberType(´M_1´, ´M_2´).
  • If ´T´ is a recursive type of the form { ´\alpha´ => ´T_1´ }:
    • The result is memberType(´T_1´, ´id´, ´p ´).
  • If ´T´ is a stable type:
    • Let ´U´ be the underlying type of ´T´.
    • The result is memberType(´U´, ´id´, ´p´).
  • Otherwise, the result is undefined.

We define the helper function mergeMemberType(´M_1´, ´M_2´) as:

  • If either ´M_1´ or ´M_2´ is undefined, the result is the other one.
  • Otherwise, if either ´M_1´ or ´M_2´ is a class result, the result is that one.
  • Otherwise, ´M_1´ and ´M_2´ must either both be term results or both be type results.
    • If they are term results with underlying types ´U_1´ and ´U_2´ and stable flags ´s_1´ and ´s_2´, the result is a term result whose underlying type is meet(´U_1´, ´U_2´) and whose stable flag is ´s_1 \lor s_2´.
    • If they are type results with underlying type definitions ´D_1´ and ´D_2´, the result is a type result whose underlying type definition is intersect(´D_1´, ´D_2´).

Relations between types

We define the following relations between types.

Name Symbolically Interpretation
Conformance ´T <: U´ Type ´T´ conforms to ("is a subtype of") type ´U´.
Equivalence ´T =:= U´ ´T´ and ´U´ conform to each other.
Weak Conformance ´T <:_w U´ Augments conformance for primitive numeric types.
Compatibility Type ´T´ conforms to type ´U´ after conversions.

Conformance

The conformance relation ´(<:)´ is the smallest relation such that ´S <: T´ is true if any of the following conditions hold.
Note that the conditions are not all mutually exclusive.

  • ´S = T´ (i.e., conformance is reflexive by definition).
  • ´S´ is Nothing.
  • ´T´ is AnyKind.
  • ´S´ is a stable type with underlying type ´S_1´ and ´S_1 <: T´.
  • ´S = p.x´ and ´T = q.x´ are term designators and
    • isSubPrefix(´p´, ´q´).
  • ´S = p.X[S_1, ..., S_n]´ and ´T = q.X[T_1, ..., T_n]´ are possibly parameterized type designators with ´n \geq 0´ and:
    • isSubPrefix(´p´, ´q´), and
    • it is not the case that ´p.x´ and ´q.X´ are class type designators for different classes, and
    • for each ´i \in { 1, ..., n }´:
      • the ´i´th type parameter of ´q.X´ is covariant and ´S_i <: T_i´ [^argisnotwildcard], or
      • the ´i´th type parameter of ´q.X´ is contravariant and ´T_i <: S_i´ [^argisnotwildcard], or
      • the ´i´th type parameter of ´q.X´ is invariant and:
        • ´S_i´ and ´T_i´ are types and ´S_i =:= T_i´, or
        • ´S_i´ is a type and ´T_i´ is a wildcard type argument of the form ´? >: L_2 <: H_2´ and ´L_2 <: S_i´ and ´S_i <: H_2´, or
        • ´S_i´ is a wildcard type argument of the form ´? >: L_1 <: H_1´ and ´T_i´ is a wildcard type argument of the form ´? >: L_2 <: H_2´ and ´L_2 <: L_1´ and ´H_1 <: H_2´ (i.e., the ´S_i´ "interval" is contained in the ´T_i´ "interval").
  • ´T = q.C[T_1, ..., T_n]´ with ´n \geq 0´ and baseType(´S´, ´C´) is defined and baseType(´S´, ´C´) ´<: T´.
  • ´S = p.X[S_1, ..., S_n]´ and ´p.X´ is non-class type designator and ´H <: T´ where ´H´ is the upper bound of the underlying type definition of ´p.X´.
  • ´S = p.C´ and ´T = C´.this and ´C´ is the hidden class of an object and:
    • ´p = \epsilon´ or ´p´ is a package ref, or
    • isSubPrefix(´p´, ´D´.this) where ´D´ is the enclosing class of ´C´.
  • ´S = C´.this and ´T = q.C´ and ´C´ is the hidden class of an object and:
    • either ´q = \epsilon´ or ´q´ is a package ref, or
    • isSubPrefix(´D´.this, ´q´) where ´D´ is the enclosing class of ´C´.
  • ´S = S_1 | S_2´ and ´S_1 <: T´ and ´S_2 <: T´.
  • ´T = T_1 | T_2´ and either ´S <: T_1´ or ´S <: T_2´.
  • ´T = T_1 & T_2´ and ´S <: T_1´ and ´S <: T_2´.
  • ´S = S_1 & S_2´ and either ´S_1 <: T´ or ´S_2 <: T´.
  • ´S = S_1´ @a and ´S_1 <: T´.
  • ´T = T_1´ @a and ´S <: T_1´ (i.e., annotations can be dropped).
  • ´T = q.X´ and ´q.X´ is a non-class type designator and ´S <: L´ where ´L´ is the lower bound of the underlying type definition of ´q.X´.
  • ´S = p.X´ and ´p.X´ is a non-class type designator and ´H <: T´ where ´H´ is the upper bound of the underlying type definition of ´p.X´.
  • ´S = [\pm a_1 >: L_1 <: H_1, ..., \pm a_n >: L_n <: H_n]´ =>> ´S_1´ and ´T = [\pm b_1 >: M_1 <: G_1, ..., \pm b_n >: M_n <: G_n]´ =>> ´T_1´, and given ´\sigma = [b_1 := a_1, ..., b_n := a_n]´:
    • ´S_1 <: \sigma T_1´, and
    • for each ´i \in { 1, ..., n }´:
      • the variance of ´a_i´ conforms to the variance of ´b_i´ (´+´ conforms to ´+´ and ´\epsilon´, ´-´ conforms to ´-´ and ´\epsilon´, and ´\epsilon´ conforms to ´\epsilon´), and
      • ´\sigma (>: M_i <: G_i)´ is contained in ´>: L_i <: H_i´ (i.e., ´L_i <: \sigma M_i´ and ´\sigma G_i <: H_i´).
  • ´S = p.X´ and ´T = [\pm b_1 >: M_1 <: G_1, ..., \pm b_n >: M_n <: G_n]´ =>> ´T_1´ and ´S´ is a type constructor with ´n´ type parameters and:
    • ´([\pm a_1 >: L_1 <: H_1, ..., \pm a_n >: L_n <: H_n]´ =>> ´S[a_1, ..., a_n]) <: T´ where the ´a_i´ are copies of the type parameters of ´S´ (i.e., we can eta-expand ´S´ to compare it to a type lambda).
  • ´T = T_1´ { ´R´ } and ´S <: T_1´ and, given ´p = S´ if ´S´ is a stable type and ´p = ∃ \alpha : S´ otherwise:
    • ´R =´ type ´X >: L <: H´ and memberType(´p´, ´X´) is a class result for ´C´ and ´L <: p.C´ and ´p.C <: H´, or
    • ´R =´ type ´X >: L_2 <: H_2´ and memberType(´p´, ´X´) is a type result with bounds ´>: L_1 <: H_1´ and ´L_2 <: L_1´ and ´H_1 <: H_2´, or
    • ´R =´ val ´X: T_2´ and memberType(´p´, ´X´) is a stable term result with type ´S_2´ and ´S_2 <: T_2´, or
    • ´R =´ def ´X: T_2´ and memberType(´p´, ´X´) is a term result with type ´S_2´ and ´T_2´ is a type and ´S_2 <: T_2´, or
    • ´R =´ def ´X: T_2´ and memberType(´p´, ´X´) is a term result with methodic type ´S_2´ and ´T_2´ is a methodic type and matches(´S_2´, ´T_2´).
  • ´S = S_1´ { ´R´ } and ´S_1 <: T´.
  • ´S =´ { ´\alpha´ => ´S_1´ } and ´T =´ { ´\beta´ => ´T_1´ } and ´S_1 <: [\beta := \alpha]T_1´.
  • ´T =´ { ´\beta´ => ´T_1´ } and ´S´ is a proper type but not a recursive type and ´p' <: [\beta := p]T_1´ where:
    • ´p´ is ´S´ if ´S´ is a stable type and ´∃ \alpha : S´ otherwise, and
    • ´p'´ is the result of replacing any top-level recursive type { ´\gamma´ => ´Z´ } in ´p´ with ´[\gamma := p]Z´ (TODO specify this better).
  • ´(X´ match <: ´H´ { ... }´) <: T´ if ´X´ match ... reduces to ´S_1´ and ´S_1 <: T´
  • ´S <: (X´ match <: ´H´ { ... }´)´ if ´X´ match ... reduces to ´T_1´ and ´S <: T_1´
  • ´(X´ match <: ´H´ { ... }´) <: T´ if ´H <: T´
  • ´(X´ match <: ´H_X´ { case ´P_1´ => ´A_1´; ...; case ´P_n´ => ´A_n´ }´) <: (Y´ match <: ´H_Y´ { case ´Q_1´ => ´B_1´; ...; ´Q_n´ => ´B_n´ }´)´ if ´X =:= Y´ and ´P_i =:= Q_i´ for each ´i´ and ´A_i <: B_i´ for each ´i´
  • ´S = (´=> ´S_1)´ and ´T = (´=> ´T_1)´ and ´S_1 <: T_1´.
  • ´S =´ scala.Null and:
    • ´T = q.C[T_1, ..., T_n]´ with ´n \geq 0´ and ´C´ does not derive from scala.AnyVal and ´C´ is not the hidden class of an object, or
    • ´T = q.x´ is a term designator with underlying type ´U´ and scala.Null ´<: U´, or
    • ´T = T_1´ { ´R´ } and scala.Null ´<: T_1´, or
    • ´T =´ { ´\beta´ => ´T_1´ } and scala.Null ´<: T_1´.
  • ´S´ is a stable type and ´T = q.x´ is a term designator with underlying type ´T_1´ and ´T_1´ is a stable type and ´S <: T_1´.
  • ´S = S_1´ { ´R´ } and ´S_1 <: T´.
  • ´S =´ { ´\alpha´ => ´S_1´ } and ´S_1 <: T´.
  • ´T =´ scala.Tuple´_n[T_1, ..., T_n]´ with ´1 \leq n \leq 22´, and ´S <: T_1´ *: ... *: ´T_n´ *: scala.EmptyTuple.

We define isSubPrefix(´p´, ´q´) where ´p´ and ´q´ are prefixes as:

  • If both ´p´ and ´q´ are types, then ´p <: q´.
  • Otherwise, ´p = q´ (for empty prefixes and package refs).

We define matches(´S´, ´T´) where ´S´ and ´T´ are types or methodic types as:

  • If ´S´ and ´T´ are types, then ´S <: T´.
  • If ´S´ and ´T´ are method types ´(a_1: S_1, ..., a_n: S_n)S'´ and ´(b_1: T_1, ..., b_n: T_n)T'´, then ´\sigma S_i =:= T_i´ for each ´i´ and matches(´\sigma S'´, ´T'´), where ´\sigma = [a_1 := b_1, ..., a_n := b_n]´.
  • If ´S´ and ´T´ are poly types ´[a_1 >: L_{s1} <: H_{s1}, ..., a_n >: L_{sn} <: H_{sn}]S'´ and ´[b_1 >: L_{t1} <: H_{t1}, ..., b_n >: L_{tn} <: H_{tn}]T'´, then ´\sigma L_{si} =:= L_{ti}´ and ´\sigma H_{si} =:= H_{ti}´ for each ´i´ and matches(´\sigma S'´, ´T'´), where ´\sigma = [a_1 := b_1, ..., a_n := b_n]´.

Note that conformance in Scala is not transitive.
Given two abstract types ´A´ and ´B´, and one abstract type ´C >: A <: B´ available on prefix ´p´, we have ´A <: p.C´ and ´C <: p.B´ but not necessarily ´A <: B´.

[^argisnotwildcard]: In these cases, if T_i and/or U_i are wildcard type arguments, the simplification rules for parameterized types allow to reduce them to real types.

Least upper bounds and greatest lower bounds

The ´(<:)´ relation forms pre-order between types, i.e. it is transitive and reflexive.
This allows us to define least upper bounds and greatest lower bounds of a set of types in terms of that order.

  • the least upper bound of A and B is the smallest type L such that A <: L and B <: L.
  • the greatest lower bound of A and B is the largest type G such that G <: A and G <: B.

By construction, for all types A and B, the least upper bound of A and B is A | B, and their greatest lower bound is A & B.

Equivalence

Equivalence is defined as mutual conformance.

´S =:= T´ if and only if both ´S <: T´ and ´T <: S´.

Weak Conformance

In some situations Scala uses a more general conformance relation.
A type ´S´ weakly conforms 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.

scala
Byte  ´<:_w´ Short
Short ´<:_w´ Int
Char  ´<:_w´ Int
Int   ´<:_w´ Long
Long  ´<:_w´ Float
Float ´<:_w´ Double

A weak least upper bound is a least upper bound with respect to weak conformance.

Compatibility

A type ´T´ is compatible to a type ´U´ if ´T´ (or its corresponding function type) weakly conforms to ´U´ after applying eta-expansion.
If ´T´ is a method type, it's converted to the corresponding function type.
If the types do not weakly conform, the following alternatives are checked in order:

  • dropping by-name modifiers: if ´U´ is of the shape ´=> U'´ (and ´T´ is not), ´T <:_w U'´;
  • SAM conversion: if ´T´ corresponds to a function type, and ´U´ declares a single abstract method whose type corresponds to the function type ´U'´, ´T <:_w U'´.
  • implicit conversion: there's an implicit conversion from ´T´ to ´U´ in scope;

Examples

Function compatibility via SAM conversion

Given the definitions

scala
def foo(x: Int => String): Unit
def foo(x: ToString): Unit

trait ToString { def convert(x: Int): String }

The application foo((x: Int) => x.toString) resolves to the first overload, as it's more specific:

  • Int => String is compatible to ToString -- when expecting a value of type ToString, you may pass a function literal from Int to String, as it will be SAM-converted to said function;
  • ToString is not compatible to Int => String -- when expecting a function from Int to String, you may not pass a ToString.

Realizability

A type ´T´ is realizable if and only if it is inhabited by non-null values.
It is defined as:

  • A term designator ´p.x´ with underlying type ´U´ is realizable if ´p´ is ´\epsilon´ or a package ref or a realizable type and
    • memberType(´p´, ´x´) has the stable flag, or
    • the type returned by memberType(´p´, ´x´) is realizable.
  • A stable type that is not a term designator is realizable.
  • Another type ´T´ is realizable if
    • ´T´ is concrete, and
    • ´T´ has good bounds.

A concrete type ´T´ has good bounds if all of the following apply:

  • all its non-class type members have good bounds, i.e., their bounds ´L´ and ´H´ are such that ´L <: H´,
  • all its type refinements have good bounds, and
  • for all base classes ´C´ of ´T´:
    • baseType(´T´, ´C´) is defined with some result ´p.C[T_1, ..., T_n]´, and
    • for all ´i \in { 1, ..., n }´, ´T_i´ is a real type or (when it is a wildcard type argument) it has good bounds.

Note: it is possible for baseType(´T´, ´C´) not to be defined because of the meet computation, which may fail to merge prefixes and/or invariant type arguments.

Type Erasure

A 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|´ for the erasure of type ´T´.
The erasure mapping is defined as follows.
Internal computations are performed in a transparent mode, which has an effect on how memberType behaves for opaque type aliases.

  • The erasure of AnyKind is Object.
  • The erasure of a non-class type designator is the erasure of its underlying upper bound.
  • The erasure of a term designator is the erasure of its underlying type.
  • The erasure of the parameterized type scala.Array´[T_1]´ is scala.Array´[|T_1|]´.
  • The erasure of every other parameterized type ´T[T_1, ..., T_n]´ is ´|T|´.
  • The erasure of a stable type ´p´ is the erasure of the underlying type of ´p´.
  • The erasure of a by-name type => ´T_1´ is scala.Function0.
  • The erasure of an annotated type ´T_1 a´ is ´|T_1|´.
  • The erasure of a refined type ´T_1´ { ´R´ } is ´|T_1|´.
  • The erasure of a recursive type { ´\alpha´ => ´T_1´ } and the associated recursive this type ´\alpha´ is ´|T_1|´.
  • The erasure of a union type ´S | T´ is the erased least upper bound (elub) of the erasures of ´S´ and ´T´.
  • The erasure of an intersection type ´S & T´ is the eglb (erased greatest lower bound) of the erasures of ´S´ and ´T´.

The erased LUB is computed as follows:

  • if both argument are arrays of objects, an array of the erased LUB of the element types
  • if both arguments are arrays of same primitives, an array of this primitive
  • if one argument is array of primitives and the other is array of objects, Object
  • if one argument is an array, Object
  • otherwise a common superclass or trait S of the argument classes, with the following two properties:
    • S is minimal: no other common superclass or trait derives from S, and
    • S is last: in the linearization of the first argument type ´|A|´ there are no minimal common superclasses or traits that come after S.
      The reason to pick last is that we prefer classes over traits that way, which leads to more predictable bytecode and (?) faster dynamic dispatch.

The rules for ´eglb(A, B)´ are given below in pseudocode:

text
eglb(scala.Array[A], JArray[B]) = scala.Array[eglb(A, B)]
eglb(scala.Array[T], _)         = scala.Array[T]
eglb(_, scala.Array[T])         = scala.Array[T]
eglb(A, B)                      = A                     if A extends B
eglb(A, B)                      = B                     if B extends A
eglb(A, _)                      = A                     if A is not a trait
eglb(_, B)                      = B                     if B is not a trait
eglb(A, _)                      = A                     // use first

Spec 04 Basic Definitions (`docs/_spec/04-basic-definitions.md`)


title: Basic Definitions layout: default chapter: 4

Basic Definitions

ebnf
PatVarDef   ::=  ‘val’ PatDef
              |  ‘var’ VarDef
Def         ::=  PatVarDef
              |  ‘def’ FunDef
              |  ‘type’ {nl} TypeDef
              |  ‘opaque‘ ‘type‘ {nl} OpaqueTypeDef
              |  TmplDef

A definition introduces names that denote terms and assigns them types, or that denote types and assigns them type definitions.
It can form part of an object or class definition or it can be local to a block.

The scope of a name introduced by a definition is the whole statement sequence containing the definition.
However, there is a restriction on forward references in blocks:
In a statement sequence ´s_1 ... s_n´ making up a block, if a simple name in ´s_i´ refers to an entity defined by ´s_j´ where ´j \geq i´, then for all ´s_k´ between and including ´s_i´ and ´s_j´,

  • ´s_k´ cannot be a variable definition.
  • If ´s_k´ is a value definition, it must be lazy.

Moreover, in a block, all term definitions must be concrete, and opaque type alias definitions are not allowed.

Value Definitions

ebnf
PatVarDef    ::=  ‘val’ PatDef
PatDef       ::=  Pattern2 {‘,’ Pattern2} [‘:’ Type] [‘=’ Expr]
ids          ::=  id {‘,’ id}

An abstract value definition val ´x´: ´T´ introduces ´x´ as a name of a value of declared type ´T´.
´T´ must be explicitly specified and must be a proper type.

A concrete value definition val ´x´: ´T´ = ´e´ defines ´x´ as a name of the value that results from the evaluation of ´e´.
If the value definition is not recursive, the declared type ´T´ may be omitted, in which case the packed type of the expression ´e´ is assumed.
If a type ´T´ is given, then it must be a proper type and ´e´ is expected to conform to it.

Evaluation of the value definition implies evaluation of its right-hand side ´e´, unless it 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´ the first time the value is accessed.

A constant value definition is of the form

scala
final val x = e

where e is a constant expression.
The final modifier must be present and no type annotation may be given.
References to the constant value x are themselves treated as constant expressions; in the generated code they are replaced by the definition's right-hand side e.

Concrete value definitions can alternatively have a pattern as left-hand side.
If ´p´ is some 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 ´x_1, ..., x_n´, where ´n > 1´:
scala
val ´\$x´ = ´e´ match {case ´p´ => (´x_1, ..., x_n´)}
val ´x_1´ = ´\$x´._1
...
val ´x_n´ = ´\$x´._n

Here, ´$x´ is a fresh name.

  1. If ´p´ has a unique bound variable ´x´:
scala
val ´x´ = ´e´ match { case ´p´ => ´x´ }
  1. If ´p´ has no bound variables:
scala
´e´ match { case ´p´ => () }

Example

The following are examples of value definitions

scala
val foo: Int              // abstract value definition
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.

scala
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 defined value may not end in _=.

A value definition val ´x_1, ..., x_n´: ´T´ is a shorthand for the sequence of value definitions val ´x_1´: ´T´; ...; val ´x_n´: ´T´.
A value definition val ´p_1, ..., p_n´ = ´e´ is a shorthand for the sequence of value definitions val ´p_1´ = ´e´; ...; val ´p_n´ = ´e´.
A value definition val ´p_1, ..., p_n: T´ = ´e´ is a shorthand for the sequence of value definitions val ´p_1: T´ = ´e´; ...; val ´p_n: T´ = ´e´.

Variable Definitions

ebnf
Dcl            ::=  ‘var’ VarDcl
PatVarDef      ::=  ‘var’ VarDef
VarDcl         ::=  ids ‘:’ Type
VarDef         ::=  PatDef
                 |  ids ‘:’ Type ‘=’ ‘_’

An abstract variable definition var ´x´: ´T´ is equivalent to the definition of both a getter method ´x´ and a setter method ´x´_=:

scala
def ´x´: ´T´
def ´x´_= (´y´: ´T´): Unit

An implementation of a class may implement a defined abstract variable using a concrete variable definition, or by defining the corresponding setter and getter methods.

A concrete variable definition var ´x´: ´T´ = ´e´ introduces a mutable variable with type ´T´ and initial value as given by the expression ´e´.
The type ´T´ can be omitted, in which case the type of ´e´ is assumed.
If ´T´ is given, then it must be a proper type and ´e´ is expected to conform to it.

Variable definitions can alternatively have a pattern as left-hand side.
A variable definition var ´p´ = ´e´ where ´p´ is a pattern other than a simple name or a name followed by a colon and a type is expanded in the same way as a value definition val ´p´ = ´e´, except that the free names in ´p´ are introduced as mutable variables, not values.

The name of any defined variable may not end in _=.

The right-hand-side of a mutable variable definition that is a member of a template can be the special reference scala.compiletime.uninitialized: var ´x´: ´T´ = scala.compiletime.uninitialized.
It introduces a mutable field with type ´T´ and a default initial value.
The default value depends on the type ´T´ as follows:

default type ´T´
0 Int or one of its subrange types
0L Long
0.0f Float
0.0d Double
false Boolean
() Unit
null all other types

scala.compiletime.uninitialized can never appear anywhere else.
For compatibility with Scala 2, the syntax var ´x´: ´T´ = _ is accepted as equivalent to using uninitialized.

When they occur as members of a template, both forms of concrete variable definition also introduce a setter method ´x´_= which changes the value currently assigned to the variable.
The setter has the same signatures as for an abstract variable definition.
It is then not possible to directly modify the value assigned to the variable; mutations always go through the corresponding setter.

Example

The following example shows how properties can be simulated in Scala.
It defines a class TimeOfDayVar of time values with updatable integer fields representing hours, minutes, and seconds.
Its implementation contains tests that allow only legal values to be assigned to these fields.
The user code, on the other hand, accesses these fields just like normal variables.

scala
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 definition var ´x_1, ..., x_n´: ´T´ is a shorthand for the sequence of variable definitions var ´x_1´: ´T´; ...; var ´x_n´: ´T´.
A variable definition var ´x_1, ..., x_n´ = ´e´ is a shorthand for the sequence of variable definitions var ´x_1´ = ´e´; ...; var ´x_n´ = ´e´.
A variable definition var ´x_1, ..., x_n: T´ = ´e´ is a shorthand for the sequence of variable definitions var ´x_1: T´ = ´e´; ...; var ´x_n: T´ = ´e´.

Type Member Definitions

ebnf
Dcl             ::=  ‘type’ {nl} TypeDcl
TypeDcl         ::=  id [TypeParamClause] [‘>:’ Type] [‘<:’ Type]
Def             ::=  ‘type’ {nl} TypeDef
                  |  ‘opaque‘ ‘type‘ {nl} OpaqueTypeDef
TypeDef         ::=  id [TypeParamClause] ‘=’ Type
                  |  id [TypeParamClause] ‘<:’ Type ‘=’ MatchType
OpaqueTypeDef   ::=  id [TypeParamClause] [‘>:’ Type] [‘<:’ Type] ‘=’ Type

Type members can be abstract type members, type aliases, or opaque type aliases.

A possibly parameterized abstract type member definition type ´t´[´\mathit{tps}\,´] >: ´L´ <: ´H´ declares ´t´ to be an abstract type.
If omitted, ´L´ and ´H´ are implied to be Nothing and scala.Any, respectively.

A possibly parameterized type alias definition type ´t´[´\mathit{tps}\,´] = ´T´ defines ´t´ to be a concrete type member.
The alternative type ´t´[´\mathit{tps}\,´] <: ´H´ = ´T´ match { ´Cs´ } desugars to type ´t´[´\mathit{tps}\,´] = (´T´ match { ´Cs´ } <: ´H´), i.e., a match type with an upper bound, which cannot otherwise be expressed in the concrete syntax.

A possibly parameterized opaque type alias definition opaque type ´t´[´\mathit{tps}\,´] >: ´L´ <: ´H´ = ´T´ defines ´t´ to be an opaque type alias with public bounds >: ´L´ <: ´H´ and a private alias = ´T´.

If a type parameter clause [´\mathit{tps}\,´] is present, it is desugared away according to the rules in the following section.

Desugaring of parameterized type definitions

A parameterized type definition is desugared into an unparameterized type definition whose bounds are type lambdas with explicit variance annotations.

The scope of a type parameter extends over the bounds >: ´L´ <: ´U´ or the alias = ´T´ and the type parameter clause ´\mathit{tps}´ itself.
A higher-order type parameter clause (of an abstract type constructor ´tc´) has the same kind of scope, restricted to the definition of the type parameter ´tc´.

To illustrate nested scoping, these definitions are all equivalent: 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 parameter of ´m´ is limited to the definition of ´m´.
In all of them, ´t´ is an abstract type member that abstracts over two type constructors: ´m´ stands for a type constructor that takes one type parameter and that must be a subtype of Bound, ´t´'s second type constructor parameter.
t[MutableList, Iterable] is a valid use of ´t´.

Abstract Type

A parameterized abstract type

scala
type ´t´[´\mathit{tps}\,´] >: ´L´ <: ´H´

is desugared into an unparameterized abstract type as follows:

  • If L conforms to Nothing, then,

    scala

type ´t´ >: Nothing
<: [´\mathit{tps'},´] =>> ´H´

text
- otherwise,

```scala
type ´t´ >: [´\mathit{tps'}\,´] =>> ´L´
     <: [´\mathit{tps'}\,´] =>> ´H´

If at least one of the ´\mathit{tps}´ contains an explicit variance annotation, then ´\mathit{tps'} = \mathit{tps}´, otherwise we infer the variance of each type parameter as with the user-written type lambda [´\mathit{tps}\,´] =>> ´H´.

The same desugaring applies to type parameters.
For instance,

scala
[F[X] <: Coll[X]]

is treated as a shorthand for

scala
[F >: Nothing <: [X] =>> Coll[X]]

Type Alias

A parameterized type alias

scala
type ´t´[´\mathit{tps}\,´] = ´T´

is desugared into an unparameterized type alias

scala
type ´t´ = [´\mathit{tps'}\,´] =>> ´T´

where ´\mathit{tps'}´ is computed as in the previous case.

Opaque Type Alias

A parameterized type alias

scala
type ´t´[´\mathit{tps}\,´] >: ´L´ <: ´H´ = ´T´

is desugared into an unparameterized opaque type alias as follows:

  • If L conforms to Nothing, then,

    scala

type ´t´ >: Nothing <: [´\mathit{tps'},´] =>> ´H´ = [´\mathit{tps'},´] =>> ´T´

text
- otherwise,

```scala
type ´t´ >: [´\mathit{tps'}\,´] =>> ´L´ <: [´\mathit{tps'}\,´] =>> ´H´ = [´\mathit{tps'}\,´] =>> ´T´

where ´\mathit{tps'}´ is computed as in the previous cases.

Non-Parameterized Type Member Definitions

An abstract type member definition type ´t´ >: ´L´ <: ´H´ declares ´t´ to be an abstract type whose type definition has the lower bound type ´L´ and upper bound type ´H´.

If a type definition appears as a member definition of a type, implementations of the type may implement ´t´ with any type ´T´ for which ´L <: T <: H´.
It is a compile-time error if ´L´ does not conform to ´H´.

A type alias definition type ´t´ = ´T´ defines ´t´ to be an alias name for the type ´T´.

An opaque type alias definition opaque type ´t´ >: ´L´ <: ´H´ = ´T´ defines ´t´ to be an opaque type alias with public bounds >: ´L´ <: ´H´ and a private alias = ´T´.
An opaque type alias can only be declared within a template.
It cannot be private and cannot be overridden in subclasses.
In order for the definition to be valid, ´T´ must satisfy some constraints:

  • ´L <: T´ and ´T <: H´ must be true,
  • ´T´ must not be a context function type, and
  • If ´T´ is a type lambda, its result must be a proper type (i.e., it cannot be a curried type lambda).

When viewed from within its enclosing template, an opaque type alias behaves as a type alias with type definition = ´T´.
When viewed from anywhere else, it behaves as an abstract type member with type definition >: ´L´ <: ´H´.
See memberType for the precise mechanism that governs this dual view.

The scope rules for definitions and type parameters make it possible that a type name appears in its own bounds or in its right-hand side.
However, it is a static error if a type alias refers recursively to the defined type itself.
That is, the type ´T´ in a type alias type ´t´[´\mathit{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 upper or lower bound.

Example

The following are legal type definitions:

scala
type IntList = List[Integer]
type T <: Comparable[T]
type Two[A] = Tuple2[A, A] // desugars to Two = [A] =>> Tuple2[A, A]
type MyCollection[+X] <: Iterable[X] // desugars to MyCollection <: [+X] =>> Iterable[X]

The following are illegal:

scala
type Abs = Comparable[Abs]      // recursive type alias

type S <: T                     // S, T are bounded by themselves.
type T <: S

type T >: Comparable[T.That]    // Cannot select from T.
                                // T is a type, not a value
type MyCollection <: Iterable   // The reference to the type constructor
                                // Iterable must explicitly state its type arguments.

If a type alias type ´t´ = ´S´ refers to a class type ´S´ (or to a type lambda that is the eta-expansion of class type ´S´), the name ´t´ can also be used as a constructor for objects of type ´S´.

Example

Suppose we make Pair an alias of the parameterized class Tuple2, as follows:

scala
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)
}

As a consequence, for any two types ´S´ and ´T´, the type Pair[´S´, ´T\,´] is equivalent to the type Tuple2[´S´, ´T\,´].
Pair can also be used as a constructor instead of Tuple2, as in:

scala
val x: Pair[Int, String] = new Pair(1, "abc")

Type Parameters

ebnf
TypeParamClause  ::= ‘[’ VariantTypeParam {‘,’ VariantTypeParam} ‘]’
VariantTypeParam ::= {Annotation} [‘+’ | ‘-’] TypeParam
TypeParam        ::= (id | ‘_’) [TypeParamClause] [‘>:’ Type] [‘<:’ Type] [‘:’ Type]

Type parameters appear in type definitions, class definitions, and method definitions.
In this section we consider only type parameter definitions with lower bounds >: ´L´ and upper bounds <: ´U´ whereas a discussion of context bounds : ´U´ and view bounds <% ´U´ is deferred to here.

The most general form of a proper type parameter is
´@a_1 ... @a_n´ ´\pm´ ´t´ >: ´L´ <: ´U´.
Here, ´L´, and ´U´ are lower and upper bounds that constrain possible type arguments for the parameter.
It is a compile-time error if ´L´ does not conform to ´U´.
´\pm´ is a variance, i.e. an optional prefix of either +, or -. One or 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 whole type parameter clause.
Therefore it is possible that a type parameter appears as part 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 the type parameter.
The most general form of a type constructor parameter is ´@a_1 ... @a_n \pm t[\mathit{tps}\,]´ >: ´L´ <: ´U´.

The above scoping restrictions are generalized to the case of nested type parameter clauses, which declare higher-order type parameters.
Higher-order type parameters (the type parameters of a type parameter ´t´) are only visible in their immediately surrounding 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 parameters are thus often irrelevant, they may be denoted with a ‘_’, which is nowhere visible.

Example

Here are some well-formed type parameter clauses:

scala
[S, T]
[@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:

scala
[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'.

Variance Annotations

Variance annotations indicate how instances of parameterized types vary with respect to subtyping.
A ‘+’ variance indicates a covariant dependency, a ‘-’ variance indicates a contravariant dependency, and a missing variance indication indicates an invariant dependency.

A variance annotation constrains the way the annotated type variable may appear in the type or class which binds the type parameter.
In a type definition type ´T´[´\mathit{tps}\,´] = ´S´, type ´T´[´\mathit{tps}\,´] >: ´L´ <: ´U´ or opaque type ´T´[´\mathit{tps}\,´] >: ´L´ <: ´U´ = ´S´, type parameters labeled ‘+’ must only appear in covariant position whereas type parameters labeled ‘-’ must only appear in contravariant position.
Analogously, for a class definition class ´C´[´\mathit{tps}\,´](´\mathit{ps}\,´) extends ´T´ { ´x´: ´S´ => ...}, type parameters labeled ‘+’ must only appear in covariant position in the self type ´S´ and the template ´T´, whereas type parameters 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 be itself.
The top-level of the type or template is always in covariant position.
The variance position changes at the following constructs.

  • The variance position of a method parameter is the opposite of the variance position of the enclosing parameter clause.
  • The variance position of a type parameter is the opposite of the variance position of the enclosing type parameter clause.
  • The variance position of the lower bound of a type definition or type parameter is the opposite of the variance position of the type definition or parameter.
  • The type of a mutable variable is always in invariant position.
  • The right-hand side of a type alias is always in invariant position.
  • The prefix ´p´ of a type selection ´p.T´ is always in invariant position.
  • For a type argument ´T´ of a type ´S´[´..., T, ...´]:
    • If the corresponding type parameter of ´S´ is invariant, then ´T´ is in invariant position.
    • If the corresponding type parameter of ´S´ is contravariant, the variance position of ´T´ is the opposite of the variance position of the enclosing type ´S´[´..., T, ...´].

References to the type parameters in object-private values, types, variables, or methods of the class are not checked for their variance position.
In these members the type parameter may appear anywhere without restricting its legal variance annotations.

Example

The following variance annotation is legal.

scala
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,

scala
P[IOException, String] <: P[Throwable, AnyRef]

If the members of ´P´ are mutable variables, the same variance annotation becomes illegal.

scala
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:

scala
abstract class R[+A, +B](x: A, y: B) {
  private var fst: A = x        // OK
  private var snd: B = y        // OK
}

Example

The following variance annotation is illegal, since ´A´ appears in contravariant position in the parameter of append:

scala
abstract class Sequence[+A] {
  def append(x: Sequence[A]): Sequence[A]
                  // **** error: illegal variance:
                  // `A' occurs in contravariant position.
}

The problem can be avoided by generalizing the type of append by means of a lower bound:

scala
abstract class Sequence[+A] {
  def append[B >: A](x: Sequence[B]): Sequence[B]
}

Example

scala
abstract class OutputChannel[-A] {
  def write(x: A): Unit
}

With that annotation, we have that OutputChannel[AnyRef] conforms to OutputChannel[String].
That is, a channel on which one can write any object can substitute for a channel on which one can write only strings.

Method Definitions

ebnf
Def                ::=  ‘def’ FunDef
FunDef             ::=  FunSig [‘:’ Type] [‘=’ Expr]
FunSig             ::=  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 ‘*’

An abstract method definition has the form def ´f\,\mathit{psig}´: ´T´, where ´f´ is the method's name, ´\mathit{psig}´ is its parameter signature and ´T´ is its result type.
A concrete method definition def ´f\,\mathit{psig}´: ´T´ = ´e´ also includes a method body ´e´, i.e. an expression which defines the method's result.
A parameter signature consists of an optional type parameter clause [´\mathit{tps}\,´], followed by zero or more value parameter clauses (´\mathit{ps}_1´)...(´\mathit{ps}_n´).

If there is no type or term parameter clause, a method definition introduces a method with a proper type, which is also its result type.
Otherwise, it introduces a method with a methodic type whose parameter types and result type are as given.

The type of the method body is expected to conform to the method's declared result type, if one is given.
If the method definition is not recursive, the result type may be omitted, in which case it is determined from the packed type of the method body.

A type parameter clause ´\mathit{tps}´ consists of one or more type definitions, which introduce type parameters, possibly with bounds.
The scope of a type parameter includes the whole signature, including any of the type parameter bounds as well as the method body, if it is present.

A value parameter clause ´\mathit{ps}´ consists of zero or more formal parameter bindings such as ´x´: ´T´ or ´x: T = e´, which bind value parameters and associate them with their types.

A unary operator must not have explicit parameter lists even if they are empty.
A unary operator is a method named "unary_´op´" where ´op´ is one of +, -, !, or ~.

Default Arguments

Each value parameter may optionally define a default argument.
The default argument expression ´e´ is type-checked with an expected type ´T'´ obtained by replacing all occurrences of the method's type parameters in ´T´ by the undefined type.

For every parameter ´p_{i,j}´ with a default argument, a method named ´f\$´default´\$´n is generated which computes the default argument expression.
Here, ´n´ denotes the parameter's position in the method definition.
These methods are parametrized by the type parameter clause [´\mathit{tps}\,´] and all value parameter clauses (´\mathit{ps}_1´)...(´\mathit{ps}_{i-1}´) preceding ´p_{i,j}´.
The ´f\$´default´\$´n methods are inaccessible for user programs.

Example

In the method

scala
def 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.
The methods computing the default arguments have the form:

scala
def compare´\$´default´\$´1[T]: Int = 0
def compare´\$´default´\$´2[T](a: T): T = a

The scope of a formal value parameter name ´x´ comprises all subsequent parameter clauses, as well as the method return type and the method body, if they are given.
Both type parameter names and value parameter names must be pairwise distinct.

A default value which depends on earlier parameters uses the actual arguments if they are provided, not the default arguments.

scala
def f(a: Int = 0)(b: Int = a + 1) = b // OK
// def f(a: Int = 0, b: Int = a + 1)  // "error: not found: value a"
f(10)()                               // returns 11 (not 1)

If an implicit argument is not found by implicit search, it may be supplied using a default argument.

scala
implicit val i: Int = 2
def f(implicit x: Int, s: String = "hi") = s * x
f                                     // "hihi"

By-Name Parameters

ebnf
ParamType          ::=  ‘=>’ Type

The type of a value parameter may be prefixed by =>, e.g. ´x´: => ´T´.
The type of such a parameter is then the by-name type => ´T´.
This indicates that the corresponding argument is not evaluated at the point of method application, but instead is evaluated at each use within the method.
That is, the argument is evaluated using call-by-name.

The by-name modifier is disallowed for parameters of classes that carry a val or var prefix, including parameters of case classes for which a val prefix is implicitly generated.

Example

The definition

scala
def whileLoop (cond: => Boolean) (stat: => Unit): Unit

indicates that both parameters of whileLoop are evaluated using call-by-name.

Repeated Parameters

ebnf
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´* take a variable number of arguments of type ´T´.
That is, if a method ´m´ with type (´p_1:T_1, ..., p_n:T_n, p_s:S´*)´U´ is applied to arguments ´(e_1, ..., e_k)´ where ´k \geq n´, then ´m´ is taken in that application to have type ´(p_1:T_1, ..., p_n:T_n, p_s:S, ..., p_{s'}:S)U´, with ´k - n´ occurrences of type ´S´ where any parameter names beyond ´p_s´ are fresh. 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 arguments (´e_1, ..., e_n, e'´: _*), then the type of ´m´ in that application is taken to be (´p_1:T_1, ... , p_n:T_n,p_{s}:´scala.Seq[´S´]).

It is not allowed to define any default arguments in a parameter section with a repeated parameter.

Example

The following method definition computes the sum of the squares of a variable number of integer arguments.

scala
def sum(args: Int*) = {
  var result = 0
  for (arg <- args) result += arg
  result
}

The following applications of this method yield 0, 1, 6, in that order.

scala
sum()
sum(1)
sum(1, 2, 3)

Furthermore, assume the definition:

scala
val xs = List(1, 2, 3)

The following application of method sum is ill-formed:

scala
sum(xs)       // ***** error: expected: Int, found: List[Int]

By contrast, the following application is well formed and yields again the result 6:

scala
sum(xs: _*)

Method Return Type Inference

A class member definition ´m´ that overrides some other method ´m'´ in a base class of ´C´ may leave out the return type, even if it is recursive.
In this case, whether or not m is recursive, its return type will be the return type of ´m'´.

Example

Assume the following definitions:

scala
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.

Tail-Recursive Call Elimination

Method definitions which contain self-recursive invocations in tail position are optimized for stack safety.
Self-invocations which are the last operation before returning from the method are replaced with jumps to the beginning of the method, much as in a while loop.
Sibling-invocations, in which a method calls itself but with a different instance as receiver, are also optimized.

This transform is performed automatically by the compiler whenever possible.
A method definition bearing the annotation, scala.annotation.tailrec, will fail to compile if the transform is not possible.
(The annotation is intended for cases where deoptimization would likely result in a stack overflow.)

scala
@annotation.tailrec
def sum(xs: List[Int], acc: Int): Int =
  xs match { case h :: t => sum(t, acc + h) case _ => acc }

Import Clauses

text
Import            ::=  ‘import’ ImportExpr {‘,’ ImportExpr}
ImportExpr        ::= SimpleRef {‘.’ id} ‘.’ ImportSpecifier
                    | SimpleRef `as` id
ImportSpecifier   ::=  NamedSelector
                    |  WildcardSelector
                    | ‘{’ ImportSelectors ‘}’
NamedSelector     ::=  id [(‘as’ | ’=>’) (id | ‘_’)]
WildcardSelector  ::=  ‘*’ | ’_’ | ‘given’ [InfixType]
ImportSelectors   ::=  NamedSelector [‘,’ ImportSelectors]
                    |  WildCardSelector {‘,’ WildcardSelector}
  • In a NamedSelector, => can only be used when inside an ImportSelectors and is then equivalent to as, to be deprecated in the future.
  • In a WildcardSelector, _ is equivalent to *, to be deprecated in the future.

An ImportSpecifier that is a single NamedSelector or WildcardSelector is equivalent to an ‘{‘ ImportSelectors ‘}‘ list with that single selector.

An import clause with multiple import expressions import ´p_1´.´I_1, ..., p_n´.´I_n´ is interpreted as a sequence of import clauses import ´p_1´.´I_1´; ...; import ´p_n´.´I_n´.

An import clause with a single import expression has the form import ´p´.´I´ where ´p´ is a prefix and ´I´ is an import specifier.
The import specifier determines a set of names of importable members of ´p´ which are made available without qualification as well as a set of importable given members which are made available in the implicit scope.
A member ´m´ of ´p´ is importable if it is accessible.
The most general form of an import specifier is a list of import selectors

scala
{ ´x_1´ as ´y_1, ..., x_n´ as ´y_n´, *, given ´T_1´, ..., given ´T_m´, given }

for ´n \geq 0´ and ´m \geq 0´, where the wildcards ‘*’ and ’given’ may be absent.
They are decomposed into non-given selectors and given selectors.

Non-given Imports

Non-given selectors make available each importable member ´p´.´x_i´ under the unqualified name ´y_i´.
In other words, every import selector ´x_i´ as ´y_i´ renames ´p´.´x_i´ to ´y_i´.
When as ´y_i´ is omitted, ´y_i´ is assumed to be ´x_i´.
If a final wildcard ‘*’ is present, all non-given importable members ´z´ of ´p´ other than ´x_1, ..., x_n, y_1, ..., y_n´ are also made available under their own unqualified names.

Non-given import selectors work in the same way for type and term members.
For instance, an import clause import ´p´.´x´ as ´y´ renames the term name ´p´.´x´ to the term name ´y´ and the type name ´p´.´x´ to the type name ´y´.
At least one of these two names must reference an importable member of ´p´.

If the target in an import selector is an underscore as _, the import selector hides access to the source member instead of importing it.
For instance, the import selector ´x´ as _ “renames” ´x´ to the underscore symbol (which is not accessible as a name in user programs), and thereby effectively prevents unqualified access to ´x´.
This is useful if there is a final wildcard in the same import selector list, which imports all members not mentioned in previous import selectors.

The scope of a binding introduced by a non-given import clause starts immediately after the import clause and extends to the end of the enclosing block, template, package clause, or compilation unit, whichever comes first.

Given Imports

Given selectors make available in the implicit scope all the importable given and implicit members ´p´.´x´ such that ´p.x´ is a subtype of ´T_i´.
A bare given selector without type is equivalent to given scala.Any.

The names of the given members are irrelevant for the selection, and are not made available in the normal scope of unqualified names.

Example

Consider the object definition:

scala
object M {
  def z = 0
  def one = 1
  def add(x: Int, y: Int): Int = x + y
}

Then the block

scala
{
  import M.{one, z as zero, *}
  add(zero, one)
}

is equivalent to the block

scala
{
  M.add(M.z, M.one)
}

Spec 05 Classes And Objects (`docs/_spec/05-classes-and-objects.md`)


title: Classes & Objects layout: default chapter: 5

Classes and Objects

ebnf
TmplDef          ::= [‘case’] ‘class’ ClassDef
                  |  [‘case’] ‘object’ ObjectDef
                  |  ‘trait’ TraitDef

Classes and objects are both defined in terms of templates.

Templates

ebnf
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 trait or class of objects or of a single object.
Templates form part of instance creation expressions, class definitions, and object definitions.
A template ´sc´ with ´mt_1´ with ... with ´mt_n´ { ´\mathit{stats}´ } consists of a constructor invocation ´sc´ which defines the template's superclass, trait references ´mt_1, ..., mt_n´ ´(n \geq 0)´, which define the template's traits, and a statement sequence ´\mathit{stats}´ which contains initialization code and additional member definitions for the template.

Each trait reference ´mt_i´ must denote a trait.
By contrast, the superclass constructor ´sc´ normally refers to a class which is not a trait.
It is possible to write a list of parents that starts with a trait reference, e.g. ´mt_1´ with ... with ´mt_n´.
In that case the list of parents is implicitly extended to include the supertype of ´mt_1´ as the first parent type.
The new supertype must have at least one constructor that does 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 regular superclass constructor, not a trait reference.

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 superclasses of all the traits ´mt_1, ..., mt_n´.
In other words, the non-trait classes inherited by a template form a chain in the inheritance hierarchy which starts with the template's superclass.

It is forbidden for a template's superclass constructor ´sc´ to be an enum class, unless the template is the implementation of an enum case of ´sc´.

The least proper supertype of a template is the class type or compound type consisting of all its parent class types.

The statement sequence ´\mathit{stats}´ contains member definitions that define new members or overwrite members in the parent classes.
If the template forms part of an abstract class or trait definition, the statement part ´\mathit{stats}´ may also contain definitions of abstract members.
If the template forms part of a concrete class definition, ´\mathit{stats}´ may still contain definitions of abstract type members, but not of abstract term members.
Furthermore, ´\mathit{stats}´ may in any case also contain expressions; these are 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 definition and an arrow, e.g. ´x´ =>, or ´x´:´T´ =>.
If a formal parameter is given, it can be 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´ of the underlying class or object as follows:
Let ´C´ be the type of the class or trait or object 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 the template, 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 type ´S´ for this without introducing an alias name for it.

Example

Consider the following class definitions:

scala
class Base extends Object {}
trait Mixin extends Base {}
object O extends Mixin {}

In this case, the definition of O is expanded to:

scala
object O extends Base with Mixin {}

Inheriting from Java Types

A template may have a Java class as its superclass and Java interfaces as its mixins.

Template Evaluation

Consider a template ´sc´ with ´mt_1´ with ´mt_n´ { ´\mathit{stats}´ }.

If this is the template of a trait then its mixin-evaluation consists of an evaluation of the statement sequence ´\mathit{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.
  • Then, all base classes in the template's linearization up to the template's superclass denoted by ´sc´ are evaluated.
    evaluation happens in reverse order of occurrence in the linearization. Each evaluation occurs as follows:
    • First, arguments to ´mt_i´ are evaluated from left to right, and set as parameters of ´mt_i´.
    • ´mt_i´ is then mixin-evaluated.
  • Finally, the statement sequence ´\mathit{stats},´ is evaluated.

Constructor Invocations

ebnf
Constr  ::=  AnnotType {‘(’ [Exprs] ‘)’}

Constructor invocations define the type, members, and initial state of objects created by an instance creation expression, or of parts of an object's definition which are inherited by a class or object definition.
A constructor invocation is a method application ´x´.´c´[´\mathit{targs}´](´\mathit{args}_1´)...(´\mathit{args}_n´), where ´x´ is a stable identifier, ´c´ is a type name which either designates a class or defines an alias type for one, ´\mathit{targs}´ is a type argument list, ´\mathit{args}_1, ..., \mathit{args}_n´ are argument lists, and there is a constructor of that class which is applicable to the given arguments.
If the constructor invocation uses named or default arguments, it is transformed into a block expression using the same transformation as described here.

The prefix ´x´. can be omitted.
A type argument list can be given only if the class ´c´ takes type parameters.
Even then it can be omitted, in which case a type argument list is synthesized using local type inference.
If no explicit arguments are given, an empty list () is implicitly supplied.

An evaluation of a constructor invocation ´x´.´c´[´\mathit{targs}´](´\mathit{args}_1´)...(´\mathit{args}_n´) consists of the following steps:

  • First, the prefix ´x´ is evaluated.
  • Then, the arguments ´\mathit{args}_1, ..., \mathit{args}_n´ are evaluated from left to right.
  • Finally, the class being constructed is initialized by evaluating the template of the class referred to by ´c´.

Class Linearization

The classes reachable through transitive closure of the direct inheritance relation from a class ´C´ are called the base classes of ´C´.
Because of mixins, the inheritance relationship on base classes forms in general a directed acyclic graph.
A linearization of this graph is defined as follows.

Definition: linearization

Let ´C´ be a class with template ´C_1´ with ... with ´C_n´ { ´\mathit{stats}´ }`.
The linearization of ´C´, ´\mathcal{L}(C)´ is defined as follows:
$$
\mathcal{L}(C) = C, \mathcal{L}(C_n) ; \vec{+} ; ... ; \vec{+} ; \mathcal{L}(C_1)
$$

Here ´\vec{+}´ denotes concatenation where elements of the right operand replace identical elements of the left operand:

$$
\begin{array}{lcll}
{a, A} ;\vec{+}; B &=& a, (A ;\vec{+}; B) &{\bf if} ; a \not\in B \\
&=& A ;\vec{+}; B &{\bf if} ; a \in B
\end{array}
$$

Example

Consider the following class definitions.

scala
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

scala
{ Iter, RichIterator, StringIterator, AbsIterator, AnyRef, Any }

Note that the linearization of a class refines the inheritance relation: if ´C´ is a subclass of ´D´, then ´C´ precedes ´D´ in any linearization where both ´C´ and ´D´ occur.
Linearization also satisfies the property that a linearization of a class always contains the linearization of its direct superclass as a suffix.

For instance, the linearization of StringIterator is

scala
{ StringIterator, AbsIterator, AnyRef, Any }

which is a suffix of the linearization of its subclass Iter.
The same is not true for the linearization of mixins.
For instance, the linearization of RichIterator is

scala
{ RichIterator, AbsIterator, AnyRef, Any }

which is not a suffix of the linearization of Iter.

Class Members

A class ´C´ defined by a template ´C_1´ with ... with ´C_n´ { ´\mathit{stats}´ } can define members in its statement sequence ´\mathit{stats}´ and can inherit members from all parent classes.
Scala adopts Java and C#'s conventions for static overloading of methods.
It is 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 a parent class, or whether the two co-exist as overloaded variants in ´C´, Scala uses the following definition of matching on members:

Definition: matching

A member definition ´M´ matches a member definition ´M'´, if ´M´ and ´M'´ 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´ is defined in Java and defines a method with an empty parameter list () and ´M'´ defines a parameterless method.
  4. ´M´ and ´M'´ define both polymorphic methods with equal number of argument types ´\overline T´, ´\overline T'´ and equal numbers of type parameters ´\overline t´, ´\overline t'´, say, and ´\overline T' = [\overline t'/\overline t]\overline T´.

Member definitions fall into two categories: concrete and abstract.
Members of class ´C´ are either directly defined (i.e. they appear in ´C´'s statement sequence ´\mathit{stats}´) or they are inherited.
There are two rules that determine the set of members of a class, one for each category:

A concrete member of a class ´C´ is any concrete definition ´M´ in some class ´C_i \in \mathcal{L}(C)´, except if there is a preceding clas ´C_j \in \mathcal{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 ´C_i \in \mathcal{L}(C)´, except if ´C´ contains already a concrete member ´M'´ matching ´M´, or if there is a preceding class ´C_j \in \mathcal{L}(C)´ where ´j < i´ which directly defines an abstract member ´M'´ matching ´M´.

This definition also determines the overriding relationships between matching members of a class ´C´ and its parents.
First, a concrete definition always overrides an abstract definition.
Second, for definitions ´M´ and ´M´' which are both concrete or both abstract, ´M´ overrides ´M'´ if ´M´ appears in a class that precedes (in the 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 error if a template contains two members (directly defined or inherited) with the same name and the same erased type.
Finally, a template is not allowed to contain two methods (directly defined or inherited) with the same name which both define default arguments.

Example

Consider the trait definitions:

scala
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 from trait C and member g from trait B.

Overriding

A member ´M´ of class ´C´ that matches a non-private member ´M'´ of a base class of ´C´ is said to override that member.
In this case the binding of the overriding member ´M´ must subsume the binding of the overridden member ´M'´.
Furthermore, the following restrictions on modifiers apply to ´M´ and ´M'´:

  • ´M'´ must not be a class.

  • ´M'´ must not be labeled final.

  • ´M´ must not be private.

  • 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 ´C´ or ´C'´ is contained in ´C´.

  • If ´M´ is labeled protected, then ´M'´ must also be labeled protected.

  • If ´M'´ is not an abstract member, then ´M´ must be labeled override.
    Furthermore, 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 base class of both the classes containing ´M´ and ´M'´
  • If ´M'´ is incomplete in ´C´ then ´M´ must be labeled abstract override.

  • If ´M´ and ´M'´ are both concrete value definitions, then either none of them is marked lazy or both must be marked lazy.

  • A stable member can only be overridden by a stable member.
    For example, this is not allowed:

scala
class X { val stable = 1}
class Y extends X { override var stable = 1 } // error

Another restriction applies to abstract type members:
An abstract type member with a volatile type as its upper bound may not override an abstract type member which does not have a volatile upper bound.

A special rule concerns parameterless methods.
If a parameterless method defined as def ´f´: ´T´ = ... or def ´f´ = ... overrides a method defined in Java of type ´()T'´ which has an empty parameter list, then ´f´ is also assumed to have an empty parameter list.

An overriding method inherits all default arguments from the definition in the superclass.
By specifying default arguments in the overriding method it is possible to add new defaults (if the corresponding parameter in the superclass does not have a default) or to override the defaults of the superclass (otherwise).

Example

Consider the definitions:

scala
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 is type T <: B, which fails to subsume the binding type T <: A of T
in type A.
The problem can be solved by adding an overriding definition of type T in class C:

scala
class C extends A with B { type T <: C }

Inheritance Closure

Let ´C´ be a class type.
The inheritance closure of ´C´ is the smallest set ´\mathscr{S}´ of types such that

  • ´C´ is in ´\mathscr{S}´.
  • If ´T´ is in ´\mathscr{S}´, then every type ´T'´ which forms syntactically a part of ´T´ is also in ´\mathscr{S}´.
  • If ´T´ is a class type in ´\mathscr{S}´, then all parents of ´T´ are also in ´\mathscr{S}´.

It is a static error if the inheritance closure of a class type consists of an infinite number of types.
(This restriction is necessary to make subtyping decidable[^kennedy]).

[^kennedy]: Kennedy, Pierce. On Decidability of Nominal Subtyping with Variance. in FOOL 2007

Modifiers

ebnf
Modifier          ::=  LocalModifier
                    |  AccessModifier
                    |  ‘override’
LocalModifier     ::=  ‘abstract’
                    |  ‘final’
                    |  ‘sealed’
                    |  ‘implicit’
                    |  ‘lazy’
                    |  ‘infix’
AccessModifier    ::=  (‘private’ | ‘protected’) [AccessQualifier]
AccessQualifier   ::=  ‘[’ (id | ‘this’) ‘]’

Member definitions may be preceded by modifiers which affect the accessibility and usage of the identifiers bound by them.
If several modifiers are given, their order does not matter, but the same modifier may not occur more than once.
Modifiers preceding a repeated definition apply to all constituent definitions.
The rules governing the validity and meaning of a modifier are as follows.

`private`

The private modifier can be used with any definition in a template.
Private members of a template can be accessed only from within the directly enclosing template and its companion module or companion class.

The private modifier is also valid for top-level templates.

A private modifier can be qualified with an identifier ´C´ (e.g. private[´C´]) that must denote a class or package enclosing the definition.
Members labeled with such a modifier are accessible respectively only from code inside the package ´C´ or only from code inside the class ´C´ and its companion module.

A different form of qualification is private[this].
A member ´M´ marked with 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 legal if the prefix is this or ´O´.this, for some class ´O´ enclosing the reference.
In addition, the restrictions for unqualified private apply.

Members marked private without a qualifier are called class-private, whereas members labeled with private[this] are called object-private.
A member is private if it is either class-private or object-private, but not if it is marked private[´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 not have protected or override modifiers.
They are not inherited by subclasses and they may not override definitions in parent classes.

`protected`

The protected modifier applies to class member definitions.
Protected members 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 definition.
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 its companion module.

A protected identifier ´x´ may be used as a member name in a selection ´r´.´x´ only if one of the following applies:

  • The access is within the template defining the member, or, if a qualification ´C´ is given, inside the package ´C´, or the class ´C´, or its companion module, 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 access.

A different form of qualification is protected[this].
A member ´M´ marked with 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 legal if the prefix is this or ´O´.this, for some class ´O´ enclosing the reference. In addition, the restrictions for unqualified protected apply.

`override`

The override modifier applies to class member definitions which are not themselves classes.
It is mandatory for member definitions that override some other concrete member definition in a parent class.
If an override modifier is given, there must be at least one overridden member definition (either concrete or abstract).

`abstract override`

The override modifier has an additional significance when combined with the abstract modifier.
That modifier combination is only allowed for value members of traits.

We call a member ´M´ of a template incomplete if it is either abstract, or it is labeled abstract and override and every member 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.

`abstract`

The abstract modifier is used in class definitions.
It is redundant for traits, and mandatory for all other classes which have incomplete members.
Abstract classes cannot be instantiated with a constructor invocation unless followed by mixins and/or a refinement which override all incomplete members of the class.
Only abstract classes and traits can have abstract term members.

The abstract modifier can also be used in conjunction with override for class member definitions.
In that case the previous discussion applies.

`final`

The final modifier applies to class member definitions and to class definitions.
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 object definitions.
Members of final classes or objects are implicitly also final, so the final modifier is generally redundant for them, too.
Note, however, that constant value definitions do require an explicit final modifier, even if they are defined in a final class or object.
final is permitted for abstract classes but it may not be applied to traits or incomplete members, and it may not be combined in one modifier list with sealed.

`sealed`

The sealed modifier applies to class definitions.
A sealed class may not be directly inherited, except if the inheriting template is defined in the same source file as the inherited class.
However, subclasses of a sealed class can be inherited anywhere.

`lazy`

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 access a lazy value during its initialization might lead to looping behavior.
If an exception is thrown during initialization, the value is considered uninitialized, and a later access will retry to evaluate its right hand side.

`infix`

The infix modifier applies to method definitions and type definitions.
It signals that the method or type is intended for use in infix position, even if it has an alphanumeric name.

If a method overrides another, their infix annotations must agree. Either both are annotated with infix, or none of them are.

The first non-receiver parameter list of an infix method must define exactly one parameter. Examples:

scala
infix def op1(x: S): R             // ok
infix def op2[T](x: T)(y: S): R    // ok
infix def op3[T](x: T, y: S): R    // error: two parameters
extension (x: A)
  infix def op4(y: B): R          // ok
  infix def op5(y1: B, y2: B): R  // error: two parameters

infix modifiers can also be given to type, trait or class definitions that have exactly two type parameters. An infix type like

scala
infix type op[X, Y]

can be applied using infix syntax, i.e., A op B.

Example

The following code illustrates the use of qualified private:

scala
package outerpkg.innerpkg
class Outer {
  class Inner {
    private[Outer] def f()
    private[innerpkg] def g()
    private[outerpkg] def h()
  }
}

Here, accesses to the method f can appear anywhere within Outer, but not outside it.
Accesses to method g can appear anywhere within the package outerpkg.innerpkg, as would be the case for package-private methods in Java.
Finally, accesses to method h can appear anywhere within package outerpkg, including packages contained in it.

Example

A useful idiom to prevent clients of a class from constructing new instances of that class is to declare the class abstract and sealed:

scala
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 calling the nextC method of an existing m.C object; it is not possible for clients to create objects of class m.C directly.
Indeed the following two lines are both in error:

scala
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 (example).

Class Definitions

ebnf
TmplDef           ::=  ‘class’ ClassDef
ClassDef          ::=  id [TypeParamClause] {Annotation}
                       [AccessModifier] ClassParamClauses ClassTemplateOpt
ClassParamClauses ::=  {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 is

scala
class ´c´[´\mathit{tps}\,´] ´as´ ´m´(´\mathit{ps}_1´)...(´\mathit{ps}_n´) extends ´t´    ´\quad(n \geq 0)´.

Here,

  • ´c´ is the name of the class to be defined.

  • ´\mathit{tps}´ is a non-empty list of type parameters of the class being defined.
    The scope of a type parameter is the whole class definition including the type parameter section itself.
    It is illegal to define two type parameters with the same name.
    The type parameter section [´\mathit{tps}\,´] may be omitted.
    A class with a type parameter section is called polymorphic, otherwise it is called monomorphic.

  • ´as´ is a possibly empty sequence of annotations.
    If any annotations are given, they apply to the primary constructor of the class.

  • ´m´ is an access modifier such as private or protected, possibly with a qualification.
    If such an access modifier is given it applies to the primary constructor of the class.

  • ´(\mathit{ps}_1)...(\mathit{ps}_n)´ are formal value parameter clauses for the primary constructor of the class.
    The scope of a formal value parameter includes all subsequent parameter 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 the class template ´t´.
    It is illegal to define two formal value parameters with the same name.

    If a class has no formal parameter section that is not implicit, an empty parameter section () is assumed.

    If a formal parameter definition ´x: T´ is preceded by a val or var keyword, an accessor definition for this parameter is implicitly added to the class.

    The accessor 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´_= is also implicitly added to the class.
    An invocation of that setter ´x´_=(´e´) changes the value of the parameter to the result of evaluating ´e´.

    The formal parameter definition may contain modifiers, which then carry over to the accessor definition(s).
    When access modifiers are given for a parameter, but no val or var keyword, val is assumed.
    A formal parameter prefixed by val or var may not at the same time be a call-by-name parameter.

  • ´t´ is a template of the form

    scala
    ´sc´ with ´mt_1´ with ... with ´mt_m´ { ´\mathit{stats}´ } // ´m \geq 0´

    which defines the base classes, behavior and initial state of objects of the class.
    The extends clause extends ´sc´ with ´mt_1´ with ... with ´mt_m´ can be omitted, in which case extends scala.AnyRef is assumed.
    The class body { ´\mathit{stats}´ } may also be omitted, in which case the empty body {} is assumed.

This class definition defines a type ´c´[´\mathit{tps}\,´] and a constructor which when applied to parameters conforming to types ´\mathit{ps}´ initializes instances of type ´c´[´\mathit{tps}\,´] by evaluating the template ´t´.

Example – `val` and `var` parameters

The following example illustrates val and var parameters of a class C:

scala
class C(x: Int, val y: String, var z: List[String])
val c = new C(1, "abc", List())
c.z = c.y :: c.z

Example – Private Constructor

The following class can be created only from its companion module.

scala
object Sensitive {
  def makeSensitive(credentials: Certificate): Sensitive =
    if (credentials == Admin) new Sensitive()
    else throw new SecurityViolationException
}
class Sensitive private () {
  ...
}

Constructor Definitions

ebnf
FunDef         ::= ‘this’ ParamClause ParamClauses
                   (‘=’ ConstrExpr | [nl] ConstrBlock)
ConstrExpr     ::= SelfInvocation
                |  ConstrBlock
ConstrBlock    ::= ‘{’ SelfInvocation {semi BlockStat} ‘}’
SelfInvocation ::= ‘this’ ArgumentExprs {ArgumentExprs}

A class may have additional constructors besides the primary constructor.
These are defined by constructor definitions of the form def this(´\mathit{ps}_1´)...(´\mathit{ps}_n´) = ´e´.
Such a definition introduces an additional constructor for the enclosing class, with parameters as given in the formal parameter lists ´\mathit{ps}_1 , ..., \mathit{ps}_n´, and whose evaluation is defined by the constructor expression ´e´.
The scope of each formal parameter is the subsequent parameter sections and the constructor expression ´e´.
A constructor expression is either a self constructor invocation this(´\mathit{args}_1´)...(´\mathit{args}_n´) or a block which 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 name ´C´ and type parameters [´\mathit{tps}\,´], then a self constructor invocation must generate an instance of ´C´[´\mathit{tps}\,´]; it is not permitted to instantiate formal type parameters.

The signature and the self constructor invocation of a constructor definition are type-checked and evaluated in the scope which is in effect at the point of the enclosing class definition, augmented by any type parameters of the enclosing class.
The rest of the constructor expression is type-checked and evaluated as a method body in the current class.

If there are auxiliary constructors of a class ´C´, they form together with ´C´'s primary constructor an overloaded constructor definition.
The usual rules for overloading resolution apply for constructor invocations of ´C´, including for the self constructor invocations in the constructor expressions themselves.
However, unlike other methods, constructors are never inherited.
To prevent infinite cycles of constructor invocations, there is the restriction that every self constructor invocation must refer to a constructor definition which precedes it (i.e. it must refer to either a preceding auxiliary constructor or the primary constructor of the class).

Example

Consider the class definition

scala
class LinkedList[A]() {
  var head: A = _
  var tail: LinkedList[A] = null
  def this(head: A) = { this(); this.head = head }
  def this(head: A, tail: LinkedList[A]) = { this(head); this.tail = tail }
}

This defines a class LinkedList with three constructors.
The second constructor constructs a singleton list, while the third one constructs a list with a given head and tail.

Case Classes

ebnf
TmplDef  ::=  ‘case’ ‘class’ ClassDef

If a class definition is prefixed with case, the class is said to be a case class.

A case class is required to have a parameter section that is not implicit.
The formal parameters in the first parameter section are called elements and are treated specially.
First, the value of such a parameter can be extracted as a field of a constructor pattern.
Second, a val prefix is implicitly added to such a parameter, unless the parameter already carries a val or var modifier.
Hence, an accessor definition for the parameter is generated.

A case class definition of ´c´[´\mathit{tps}\,´](´\mathit{ps}_1\,´)...(´\mathit{ps}_n´) with type parameters ´\mathit{tps}´ and value parameters ´\mathit{ps}´ implies the definition of a companion object, which serves as an extractor object.
It has the following shape:

scala
object ´c´ {
  def apply[´\mathit{tps}\,´](´\mathit{ps}_1\,´)...(´\mathit{ps}_n´): ´c´[´\mathit{tps}\,´] = new ´c´[´\mathit{Ts}\,´](´\mathit{xs}_1\,´)...(´\mathit{xs}_n´)
  def unapply[´\mathit{tps}\,´](´x´: ´c´[´\mathit{tps}\,´]) =
    if (x eq null) scala.None
    else scala.Some(´x.\mathit{xs}_{11}, ... , x.\mathit{xs}_{1k}´)
}

Here, ´\mathit{Ts}´ stands for the vector of types defined in the type parameter section ´\mathit{tps}´, each ´\mathit{xs}_i´ denotes the parameter names of the parameter section ´\mathit{ps}_i´, and ´\mathit{xs}_{11}, ... , \mathit{xs}_{1k}´ denote the names of all parameters in the first parameter section ´\mathit{xs}_1´.
If a type parameter section is missing in the class, it is also missing in the apply and unapply methods.

If the companion object ´c´ is already defined, the apply and unapply methods are added to the existing object.
If the object ´c´ already has a matching apply (or unapply) member, no new definition is added.
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:

scala
def unapply[´\mathit{tps}\,´](´x´: ´c´[´\mathit{tps}\,´]) = x ne null

The name of the unapply method is changed to unapplySeq if the first parameter section ´\mathit{ps}_1´ of ´c´ ends in a repeated parameter.

A method named copy is implicitly added to every case class unless the class already has a member (directly defined or inherited) with that name, or the class has a repeated parameter.
The method is defined as follows:

scala
def copy[´\mathit{tps}\,´](´\mathit{ps}'_1\,´)...(´\mathit{ps}'_n´): ´c´[´\mathit{tps}\,´] = new ´c´[´\mathit{Ts}\,´](´\mathit{xs}_1\,´)...(´\mathit{xs}_n´)

Again, ´\mathit{Ts}´ stands for the vector of types defined in the type parameter section ´\mathit{tps}´ and each ´xs_i´ denotes the parameter names of the parameter section ´ps'_i´.
The value parameters ´ps'_{1,j}´ of first parameter list have the form ´x_{1,j}´:´T_{1,j}´=this.´x_{1,j}´, the other parameters ´ps'_{i,j}´ of the copy method are defined as ´x_{i,j}´:´T_{i,j}´.
In all cases ´x_{i,j}´ and ´T_{i,j}´ refer to the name and type of the corresponding class parameter ´\mathit{ps}_{i,j}´.

Every case class implicitly overrides some method definitions of class scala.AnyRef unless a definition of the same method is already given in the case class itself or 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 instances are equal if they both belong to the case class in question and they have equal (with respect to equals) constructor arguments (restricted to the class's elements, i.e., the first parameter section).
  • Method hashCode: Int computes a hash-code. If the hashCode methods of the 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 contains the name of the class and its elements.

Example

Here is the definition of abstract syntax for lambda calculus:

scala
class Expr
case class Var   (x: String)          extends Expr
case class Apply (f: Expr, e: Expr)   extends Expr
case class Lambda(x: String, e: Expr) extends Expr

This 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.

scala
type Env = String => Value
case 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 the program, for instance

scala
case 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 as Expr.

Traits

ebnf
TmplDef          ::=  ‘trait’ ClassDef

A trait is a class that is meant to be added to some other class as a mixin.
Furthermore, no constructor 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 class of ´C´).
Then the actual supertype of ´D´ in ´x´ is the compound type consisting of all the base classes in ´\mathcal{L}(C)´ that succeed ´D´.
The actual supertype gives the context for resolving a super reference in a trait.
Note that the actual supertype depends on 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 (which is statically known).

Example

The following trait defines the property of being comparable to objects of some type.
It contains an abstract method < and default implementations of the other comparison operators <=, >, and >=.

scala
trait Comparable[T <: Comparable[T]] { self: T =>
  def < (that: T): Boolean
  def <=(that: T): Boolean = this < that || this == that
  def > (that: T): Boolean = that < this
  def >=(that: T): Boolean = that <= this
}

Example

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 matching a given key.
Finally, there is a method apply which is like get, except that it returns a given default value if the table is undefined for the given key.
This class is implemented as follows.

scala
abstract class Table[A, B](defaultValue: B) {
  def get(key: A): Option[B]
  def set(key: A, value: B): Unit
  def apply(key: A) = get(key) match {
    case Some(value) => value
    case None => defaultValue
  }
}

Here is a concrete implementation of the Table class.

scala
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:

scala
trait SynchronizedTable[A, B] extends Table[A, B] {
  abstract override def get(key: A): 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 in 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.

Finally, the following mixin composition creates a synchronized list table with strings as keys and integers as values and with a default value 0:

scala
object MyTable extends ListTable[String, Int](0) with SynchronizedTable[String, Int]

The object MyTable inherits its get and set method from SynchronizedTable.
The super calls in these methods are re-bound to refer to the corresponding implementations in ListTable, which is the actual supertype of SynchronizedTable in MyTable.

Extending parameterized traits

Extra rules apply for extending a trait with parameters:

  1. If a class ´C´ extends a parameterized trait ´T´, and its superclass does not, ´C´ must pass arguments to ´T´.

  2. If a class ´C´ extends a parameterized trait ´T´, and its superclass does as well, ´C´ must not pass arguments to ´T´.

  3. Traits must never pass arguments to parent traits.

  4. If a class ´C´ extends an unparameterized trait ´T_i´ and the base types of ´T_i´ include parameterized trait ´T_j´, and the superclass of ´C´ does not extend ´T_j´, then ´C´ must also explicitly extend ´T_j´ and pass arguments.
    This rule is relaxed if the missing trait contains only context parameters. In that case the trait reference is implicitly inserted as an additional parent with inferred arguments.

Example - Preventing ambiguities

The following listing tries to extend Greeting twice, with different parameters.

scala
trait Greeting(val name: String):
  def msg = s"How are you, $name"

class C extends Greeting("Bob")

class D extends C, Greeting("Bill") // error

@main def greet = println(D().msg)

Should this program print "Bob" or "Bill"? In fact this program is illegal, because it violates rule 2 above.
Instead, D can extend Greeting without passing arguments.

Example - Overriding

Here's a variant of Greeting that overrides msg:

scala
trait FormalGreeting extends Greeting:
  override def msg = s"How do you do, $name"

Due to rule 4, the following class extending FormalGreeting is required to also extend Greeting with arguments:

scala
class GreetBobFormally extends FormalGreeting, Greeting("Bob")

Example - Inferred context parameters

Here's a variant of Greeting where the addressee is a context parameter of type ImpliedName:

scala
trait ImpliedGreeting(using val iname: ImpliedName):
  def msg = s"How are you, $iname"

case class ImpliedName(name: String):
  override def toString = name

trait ImpliedFormalGreeting extends ImpliedGreeting:
  override def msg = s"How do you do, $iname"

class F(using iname: ImpliedName) extends ImpliedFormalGreeting

The definition of F in the last line is implicitly expanded to

scala
class F(using iname: ImpliedName) extends
  Object, // implicitly inserted
  ImpliedGreeting(using iname), // implicitly inserted
  ImpliedFormalGreeting

Due to rule 4, F is required to also extend ImpliedGreeting and pass arguments to it, however note that because ImpliedGreeting has only context parameters the extension was added implicitly.

Object Definitions

ebnf
TmplDef         ::=  ‘object’ ObjectDef
ObjectDef       ::=  id ClassTemplate

An object definition defines a single object of a new class.
Its most general form is object ´m´ extends ´t´.
Here, ´m´ is the name of the object to be defined, and ´t´ is a template of the form

scala
´sc´ with ´mt_1´ with ... with ´mt_n´ { ´\mathit{stats}´ }

which defines the base classes, behavior and initial state of ´m´.
The extends clause extends ´sc´ with ´mt_1´ with ... with ´mt_n´ can be omitted, in which case extends scala.AnyRef is assumed.
The class body { ´\mathit{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 template ´t´.
It is roughly equivalent to the following definition of a lazy value:

scala
lazy val ´m´ = new ´sc´ with ´mt_1´ with ... with ´mt_n´ { this: ´m.type´ => ´\mathit{stats}´ }

Note that the value defined by an object definition is instantiated lazily.
The new ´m´$cls constructor is evaluated not at the point of the object definition, but is instead evaluated the first time ´m´ is dereferenced during execution of the program (which might be never at all).
An attempt to dereference ´m´ again during evaluation of the constructor will lead to an infinite loop or run-time error.
Other threads trying to dereference ´m´ while the constructor is being evaluated block until evaluation is complete.

The expansion given above is not accurate for top-level objects.
It cannot be because variable and method definition cannot appear on the top-level outside of a package object.
Instead, top-level objects are translated to static fields.

Example

Classes in Scala do not have static members; however, an equivalent effect can be achieved by an accompanying object definition E.g.

scala
abstract class Point {
  val x: Double
  val y: Double
  def 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 a name 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 that contains all instance members of ´C´ and a Scala object that contains all static members 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, the class is called the companion class of the module.

Very much like a concrete class definition, an object definition may still contain definitions of abstract type members, but not of abstract term members.

Enum Definitions

ebnf
TmplDef   ::=  ‘enum’ EnumDef
EnumDef   ::=  id ClassConstr [‘extends’ ConstrApps] EnumBody
EnumBody  ::=  [nl] ‘{’ [SelfType] EnumStat {semi EnumStat} ‘}’
EnumStat  ::=  TemplateStat
            |  {Annotation [nl]} {Modifier} EnumCase
EnumCase  ::=  ‘case’ (id ClassConstr [‘extends’ ConstrApps] | ids)

An enum definition implies the definition of an enum class, a companion object, and one or more enum cases.

Enum definitions are useful to encode both Generalised Algebraic Data Types and Enumerated Types.

The compiler expands enum definitions to code that only uses Scala's other language features.
As such, enum definitions in Scala are convenient syntactic sugar, but they are not essential to understand Scala's core.

We now explain the expansion of enum definitions in detail.
First, some terminology and notational conventions:

  • We use ´E´ as a name of an enum definition, and ´C´ as a name of an enum case that appears in ´E´.

  • We use <...> for syntactic constructs that in some circumstances might be empty.
    For instance, <value-params> represents one or more parameter lists (´\mathit{ps}_1\,´)...(´\mathit{ps}_n´) or nothing at all.

  • Enum classes fall into two categories:

    • parameterized enum classes have at least one or more (possibly empty) term parameter clauses, denoted as (´\mathit{ps}_1\,´)...(´\mathit{ps}_n´).
    • unparameterized enum classes have no term parameter clauses, but may optionally have a type parameter clause, denoted as [´\mathit{tps}\,´].
  • Enum cases fall into three categories:

    • Class enum cases are those cases that possibly have a type parameter clause [´\mathit{tps}\,´], and necessarily have one or more (possibly empty) parameter clauses (´\mathit{ps}_1\,´)...(´\mathit{ps}_n´).
    • Simple enum cases are those cases that have no parameter clauses and no extends clause.
      That is, they consist of a name only.
    • Value enum cases are those cases that have no parameter clauses but that do have a (possibly generated) extends clause.
  • Simple enum cases and value enum cases are collectively called singleton enum cases.

Example

An example enum for a Planet enumeration can be given as

scala
enum Planet(mass: Double, radius: Double):
  case Mercury extends Planet(3.303e+23, 2.4397e6)
  case Venus   extends Planet(4.869e+24, 6.0518e6)
  case Earth   extends Planet(5.976e+24, 6.37814e6)
  case Mars    extends Planet(6.421e+23, 3.3972e6)
  case Jupiter extends Planet(1.9e+27,   7.1492e7)
  case Saturn  extends Planet(5.688e+26, 6.0268e7)
  case Uranus  extends Planet(8.686e+25, 2.5559e7)
  case Neptune extends Planet(1.024e+26, 2.4746e7)

  private inline val G = 6.67300E-11
  def surfaceGravity = G * mass / (radius * radius)
  def surfaceWeight(otherMass: Double) = otherMass * surfaceGravity
end Planet

Example

An example enum for the Option ADT can be given as

scala
enum Option[+T]:
  case Some(x: T)
  case None

Lowering of Enum Definitions

Summary

An enum class is represented as a sealed abstract class that extends the scala.reflect.Enum trait.

Enum cases are represented as follows:

  • a class enum case is mapped to a case class member of the enum class' companion object,
  • a singleton enum case is mapped to a val member of the enum class' companion object, implemented by a local class definition. Whether that local class is shared with other singleton cases, and which ones, is left as an implementation detail.

Precise rules

The scala.reflect.Enum trait defines a single public method, ordinal:

scala
package scala.reflect

transparent trait Enum extends Any, Product, Serializable:

  def ordinal: Int

There are nine desugaring rules.
Rule (1) desugars enum definitions.
Rule (2) desugars cases of comma-separated names to simple enum cases.
Rules (3) to (7) desugar inferrable details of enum cases.
Rules (8) and (9) define how fully-desugared enum cases map into case classes or vals.
Explicit extends clauses must be provided in the following cases, where rules (2) to (6) do not apply:

  • any enum case of a parameterized enum,
  • any singleton enum case of an unparameterized enum with non-variant type parameters,
  • any class enum case of an enum with type parameters, where the case also has type parameters.
  1. An enum definition

    scala
    enum ´E´ <type-params> <value-params> extends <parents> { <defs> <cases> }

    expands to a sealed abstract class that extends the scala.reflect.Enum trait and an associated companion object that contains the defined cases, expanded according to rules (2 - 8).
    The enum class starts with a compiler-generated import that imports the names <caseIds> of all cases so that they can be used without prefix in the class.

    scala
    sealed abstract class ´E´ <type-params> <value-params>
        extends <parents> with scala.reflect.Enum {
      import ´E´.{ <caseIds> }
      <defs>
    }
    object ´E´ { <cases> }
  2. A simple enum case consisting of a comma-separated list of names

    scala
    case ´C_1´, ..., ´C_n´

    expands to the following simple enum cases

    scala
    case ´C_1´; ...; case ´C_n´

    Any modifiers or annotations on the original case extend to all expanded cases.
    This result is then further rewritten by either (3 or 4).

  3. A simple enum case ´C´ of an unparameterized enum ´E´ without type parameters

    scala
    case ´C´

expands to the following value enum case:

scala
case ´C´ extends ´E´

This result is then further rewritten with rule (8).

  1. A simple enum case ´C´ of an unparameterized enum ´E´[´\mathit{tps}´] with type parameters

    scala
    case ´C´

    where ´\mathit{tps}´ are of the following form

    scala
    ´\mathit{v}_1´ ´T_1´ >: ´L_1´ <: ´U_1´ ,   ... ,   ´\mathit{v}_n´ ´T_n´ >: ´L_n´ <: ´U_n´      (n > 0)

    and where each of the variances ´\mathit{v}_i´ is either '+' or '-', expands to the following value enum case:

    scala
    case ´C´ extends ´E´[´B_1´, ..., ´B_n´]

    where ´B_i´ is ´L_i´ if ´\mathit{v}_i´ = '+' and ´U_i´ if ´\mathit{v}_i´ = '-'.
    This result is then further rewritten with rule (8).

  2. A class enum case with type parameters, but without an extends clause

    scala
    case ´C´[´\mathit{tps}´](´\mathit{ps}_1\,´)...(´\mathit{ps}_n´)

    of an unparameterized enum ´E´ without type parameters expands to

    scala
    case ´C´[´\mathit{tps}´](´\mathit{ps}_1\,´)...(´\mathit{ps}_n´) extends ´E´

    This result is then further rewritten with rule (9).

  3. A class enum case without type parameters or an extends clause

    scala
    case ´C´(´\mathit{ps}_1\,´)...(´\mathit{ps}_n´)

    of an unparameterized enum ´E´[´\mathit{tps}´] with type parameters expands to

    scala
    case ´C´(´\mathit{ps}_1\,´)...(´\mathit{ps}_n´) extends ´E´[´\mathit{tps}´]

    This result is then further rewritten with rule (7).

  4. A class enum case without type parameters, but has an extends clause

    scala
    case ´C´(´\mathit{ps}_1\,´)...(´\mathit{ps}_n´) extends <parents>

    of an enum ´E´[´\mathit{tps}´] with type parameters expands to

    scala
    case ´C´[´\mathit{tps}´](´\mathit{ps}_1\,´)...(´\mathit{ps}_n´) extends <parents>

    provided at least one of the parameters ´\mathit{tps}´ is mentioned in a parameter type in (´\mathit{ps}_1\,´)...(´\mathit{ps}_n´) or in a type argument in ``.

    This result is then further rewritten with rule (9).

  5. A singleton enum case

    scala
    case ´C´ extends <parents>

    expands to the following val definition in ´E´'s companion object:

    scala
    val ´C´ = $factory(_$ordinal = ´\mathit{n}´, $name = "C")

    where ´\mathit{n}´ is the ordinal number of the case in the companion object, starting from 0.
    $factory is a placeholder that expands its arguments into an expression that produces something equivalent to
    a new instance of the following (possibly shared) anonymous class:

    scala
    new <parents> {
       def ordinal: Int = _$ordinal
       override def toString: String = $name
    }

    The anonymous class also implements the abstract Product methods that it inherits from Enum.

    NOTE: It is an error if a value case refers to a type parameter of ´E´ in a type argument within ``.

  6. A class enum case

    scala
    case ´C´ <type-params> <value-params> extends <parents>

    expands analogous to a final case class in ´E´'s companion object:

    scala
    final case class ´C´ <type-params> <value-params> extends <parents> {
       def ordinal = ´\mathit{n}´
    }

    where ´\mathit{n}´ is the ordinal number of the case in the companion object, starting from 0.

    NOTE: It is an error if a class case refers to a type parameter of ´E´ in a parameter type in <type-params> or <value-params> or in a type argument of ``, unless that parameter is already a type parameter of the case, i.e. the parameter name is defined in <type-params>.

Superclass of an enum case

an enum case (singleton or class) with explicit extends clause

scala
case ´C´ <type-params> <value-params> extends <parents>

must extend the parent enum ´E´ as the first parent of ``.

Example

Consider the enumeration RGB, consisting of simple enum cases:

scala
enum RGB:
  case Red, Green, Blue

The three simple cases will expand as follows in the companion of RGB:

scala
val Red = $new(0, "Red")
val Green = $new(1, "Green")
val Blue = $new(2, "Blue")

private def $new(_$ordinal: Int, $name: String) =
  new RGB with scala.runtime.EnumValue:
    def ordinal = _$ordinal
    override def productPrefix = $name
    override def toString = $name

Widening of enum cases post-construction

The compiler-generated apply and copy methods of an class enum case

scala
case ´C´[´\mathit{tps}\,´](´\mathit{ps}_1\,´)...(´\mathit{ps}_n´) extends ´P_1´, ..., ´P_n´

are treated specially.
A call ´C´[´\mathit{tps}\,´](´\mathit{ps}_1\,´)...(´\mathit{ps}_n´) of the apply method is ascribed the underlying type ´P_1´ & ... & ´P_n´ (dropping any transparent traits) as long as that type is still compatible with the expected type at the point of application.
A call t.copy[´\mathit{tps}\,´](´\mathit{ps}_1\,´)...(´\mathit{ps}_n´) of ´C´'s copy method is treated in the same way.

Translation of enums with only singleton cases

An enum ´E´ (possibly generic) that defines one or more singleton cases, and no class cases will define the following additional synthetic members in its companion object (where ´E'´ denotes ´E´ with any type parameters replaced by wildcards):

  • A method valueOf(name: String): ´E'´.
    It returns the singleton case value whose identifier is name.
  • A method values which returns an Array[´E'´] of all singleton case values defined by E, in the order of their definitions.

Translation of Java-compatible enums

A Java-compatible enum is an enum that extends java.lang.Enum.
The translation rules are the same as above, with the reservations defined in this section.

  • It is a compile-time error for a Java-compatible enum to have class cases.

  • Cases such as case C expand to a @static val as opposed to a val.
    This allows them to be generated as static fields of the enum type, thus ensuring they are represented the same way as Java enums.

Scopes for Enum Cases

A case in an enum is treated similarly to a secondary constructor.
It can access neither the enclosing enum using this, nor its value parameters or instance members using simple identifiers.

Even though translated enum cases are located in the enum's companion object, referencing this object or its members via this or a simple identifier is also illegal.
The compiler typechecks enum cases in the scope of the enclosing companion object but flags any such illegal accesses as errors.

Variance for Type Parameters

A parameterized enum case ´C´ of enum ´E´ with inferred type parameters will copy variance annotations.
e.g. type parameter ´T_{i}´ from ´E´ will have the same variance as type parameter ´T'_{i}´ in ´C´.

Example

The following enum View has a contravariant type parameter ´T´ and a single case Refl, representing a function mapping a type T to itself:

scala
enum View[-´T´]:
  case Refl(f: ´T´ => ´T´)

Refl expands to the following enum:

scala
enum View[-´T´]:
  case Refl[-´T'´](f: ´T'´ => ´T'´) extends View[´T'´]

The definition of Refl is incorrectly typed, as it uses contravariant type ´T'´ in the covariant result position of a function type.

A correctly typed version would use an explicit, invariant type parameter ´R´ on case Refl:

scala
enum View[-´T´]:
  case Refl[´R´](f: ´R´ => ´R´) extends View[´R´]

Spec 06 Expressions (`docs/_spec/06-expressions.md`)


title: Expressions layout: default chapter: 6

Expressions

text
/* Detailed source-code truncated for AI context efficiency. */

Expressions are composed of operators and operands.
Expression forms are discussed subsequently in decreasing order of precedence.

Expression Typing

The typing of expressions is often relative to some expected type (which might be undefined).
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 conform to ´T´.

The following skolemization rule is applied universally for every expression:
If the type of an expression would be an existential type ´T´, then the type of the expression is assumed instead to be a skolemization of ´T´.

Skolemization is reversed by type packing.
Assume an expression ´e´ of type ´T´ and let ´t_1[\mathit{tps}_1] >: L_1 <: U_1, ..., t_n[\mathit{tps}_n] >: L_n <: U_n´ be all the type variables created by skolemization of some part of ´e´ which are free in ´T´.
Then the packed type of ´e´ is

scala
´T´ forSome { type ´t_1[\mathit{tps}\_1] >: L_1 <: U_1´; ...; type ´t_n[\mathit{tps}\_n] >: L_n <: U_n´ }.

Literals

ebnf
SimpleExpr    ::=  Literal

Typing of literals is described along with their lexical syntax; their evaluation is immediate.

The _Null_ Value

The null value is of type scala.Null, and thus conforms to every reference type.
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 default value of type ´T´.
  • ## returns 0.

A reference to any other member of the "null" object causes a NullPointerException to be thrown.

Designators

ebnf
SimpleExpr  ::=  Path
              |  SimpleExpr ‘.’ id

A 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 here.
If ´x´ is bound by a definition in an enclosing class or object ´C´, it is taken to be equivalent to the selection ´C´.this.´x´ where ´C´ is taken to refer to the class containing ´x´ even if the type name ´C´ is shadowed at the occurrence of ´x´.

If ´r´ is a stable identifier of type ´T´, the selection ´r.x´ refers statically to a term member ´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 fresh name ´y´.

The expected type of a designator's prefix is always undefined.
The type of a designator is the type ´T´ of the entity it refers to, with the following exception: The type of a path ´p´ which occurs in a context where a stable type is required is the singleton type ´p´.type.

The contexts where a stable type is required are those that satisfy one of the following conditions:

  1. The path ´p´ occurs as the prefix of a selection and it does not designate a constant, or
  2. The expected type ´\mathit{pt}´ is a stable type, or
  3. The expected type ´\mathit{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 ´\mathit{pt}´, or
  4. The path ´p´ designates a module.

The selection ´e.x´ is evaluated by first evaluating the qualifier expression ´e´, which yields an object ´r´, say.
The selection's result is then the member of ´r´ that is either defined by ´m´ or defined by a definition overriding ´m´.

This and Super

ebnf
SimpleExpr  ::=  [id ‘.’] ‘this’
              |  [id ‘.’] ‘super’ [ClassQualifier] ‘.’ id

The 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 compound type enclosing the reference.
If this is a compound type, the type of this is that compound 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 object definition with simple name ´C´.
It stands for the object being defined by the innermost such definition.
If the expression's expected type is a stable type, or ´C´.this occurs as the prefix of a selection, its type is ´C´.this.type, otherwise it is the self type of class ´C´.

A reference super.´m´ refers statically to a method or type ´m´ in the least proper supertype of the innermost template containing the reference.
It evaluates to the member ´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.

If it is a method, it must be concrete, or the template containing the reference must have 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 proper supertype of the innermost enclosing class or object definition named ´C´ which encloses 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 referenced member ´m´ must be a type or a method.
If the statically referenced member ´m´ is a method, it must be concrete, or the innermost enclosing class or object definition named ´C´ must have a member ´m'´ which overrides ´m´ and which is labeled abstract override.

The super prefix may be followed by a trait qualifier [´T\,´], as in ´C´.super[´T\,´].´x´.
This is called a static super reference.
In this case, the reference is to the type or method of ´x´ 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

Consider the following class definitions

scala
class 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:

scala
(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 method returns different results depending on whether B is mixed in with class Root or A.

Method Applications

ebnf
SimpleExpr    ::=  SimpleExpr1 ArgumentExprs
ArgumentExprs ::=  ‘(’ [Exprs] ‘)’
                |  ‘(’ ‘using’ Exprs ‘)’
                |  ‘(’ [Exprs ‘,’] PostfixExpr ‘:’ ‘_’ ‘*’ ‘)’
                |  [nl] BlockExpr
Exprs         ::=  Expr {‘,’ Expr}

An application ´f(e_1, ..., e_m)´ applies the method ´f´ to the argument expressions ´e_1, ..., e_m´.
For this expression to be well-typed, the method must be applicable to its arguments:

If ´f´ has a method type (´p_1´:´T_1, ..., p_n´:´T_n´)´U´, each argument expression ´e_i´ is typed with the corresponding parameter type ´T_i´ as expected type.
Let ´S_i´ be the type of argument ´e_i´ ´(i = 1, ..., n)´.
The method ´f´ must be applicable to its arguments ´e_1, ..., e_n´ of types ´S_1, ..., S_n´.
If the last parameter type of ´f´ is repeated, harmonization is attempted on the suffix ´e_m, ..., e_n´ of the expression list that match the repeated parameter.
We say that an argument expression ´e_i´ is a named argument if it has the form ´x_i=e'_i´ and ´x_i´ is one of the parameter names ´p_1, ..., p_n´.

Once the types ´S_i´ have been determined, the method ´f´ of the above method type is said to be applicable if all of the following conditions hold:

  • for every named argument ´p_j=e_i'´ the type ´S_i´ is compatible with the parameter type ´T_j´;
  • for every positional argument ´e_i´ the type ´S_i´ is compatible with ´T_i´;
  • if the expected type is defined, the result type ´U´ is compatible to it.

If ´f´ is instead of some value type, the application is taken to be equivalent to ´f´.apply(´e_1, ..., e_m´), i.e. the application of an apply method defined by ´f´.
Value ´f´ is applicable to the given arguments if ´f´.apply is applicable.

Notes:

  • In the case where ´f´ or ´f´.apply is a polymorphic method, this is taken as an ommitted type application.
  • ´f´ is applicable to the given arguments if the result of this type application is applicable.

The application ´f´(´e_1, ..., e_n´) evaluates ´f´ and then each argument ´e_1, ..., e_n´ from left to right, except for arguments that correspond to a by-name parameter (see below).
Each argument expression is converted to the type of its corresponding formal parameter.
After that, the application is rewritten to the method's right hand side, with actual arguments substituted for formal parameters.
The result of evaluating the rewritten right-hand side is finally converted to the method's declared result type, if one is given.

The case of a formal parameter with a parameterless method type => ´T´ is treated specially.
In this case, the corresponding actual argument expression ´e´ is not evaluated before the application.
Instead, every use of the formal parameter on the right-hand side of the rewrite rule entails a re-evaluation of ´e´.
In other words, the evaluation 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 packed type conforms to the parameter type ´T´.
The behavior of by-name parameters 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 form val ´y_i´ = () => ´e´ and the argument passed to the method is ´y_i´().

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 of type ´S´* and it must be the only argument matching this parameter (i.e. the number of formal 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 this case, 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 specified exactly once.

If only a single argument is supplied, it may be supplied as a block expression and parentheses can be omitted, in the form ´f´ { block }.
This is valid when f has a single formal parameter or when all other formal parameters have default values.

A method application usually allocates a new frame on the program's run-time stack.
However, if a local method or a final method calls itself as its last action, the call is executed using the stack-frame of the caller.

Example

Assume the following method which computes the sum of a variable number of arguments:

scala
def sum(xs: Int*) = xs.foldLeft(0)((x, y) => x + y)

Then

scala
sum(1, 2, 3, 4)
sum(List(1, 2, 3, 4): _*)

both yield 10 as result.
On the other hand,

scala
sum(List(1, 2, 3, 4))

would not typecheck.

An argument list may begin with the soft keyword using to facilitate cross-compilation with Scala 3.
The keyword is ignored.

Named and Default Arguments

If an application is to use named arguments ´p = e´ or default arguments, the following conditions must hold.

  • For every named argument ´p_i = e_i´ which appears left of a positional argument in the argument list ´e_1 ... e_m´, the argument position ´i´ coincides with the position of parameter ´p_i´ in the parameter list of the applied method.
  • The names ´x_i´ of all named arguments are pairwise distinct and no named argument defines a parameter which is already specified by a positional argument.
  • Every formal parameter ´p_j:T_j´ which is not specified by either a positional or named argument has a default argument.

If the application uses named or default arguments the following transformation is applied to convert it into an application without named or default arguments.

If the method ´f´ has the form ´p.m´[´\mathit{targs}´] it is transformed into the block

scala
{ val q = ´p´
  q.´m´[´\mathit{targs}´]
}

If the method ´f´ is itself an application expression the transformation is applied recursively on ´f´.
The result of transforming ´f´ is a block of the form

scala
{ val q = ´p´
  val ´x_1´ = expr´_1´
  ...
  val ´x_k´ = expr´_k´
  q.´m´[´\mathit{targs}´](´\mathit{args}_1´), ...,(´\mathit{args}_l´)
}

where every argument in ´(\mathit{args}_1), ..., (\mathit{args}_l)´ is a reference to one of the values ´x_1, ..., x_k´.
To integrate the current application into the block, first a value definition using a fresh name ´y_i´ is created for every argument in ´e_1, ..., e_m´, which is initialised to ´e_i´ for positional arguments and to ´e'_i´ for named arguments of the form ´x_i=e'_i´.
Then, for every parameter which is not specified by the argument list, a value definition using a fresh name ´z_i´ is created, which is initialized using the method computing the default argument of this parameter.

Let ´\mathit{args}´ be a permutation of the generated names ´y_i´ and ´z_i´ such such that the position of each name matches the position of its corresponding parameter in the method type (´p_1:T_1, ..., p_n:T_n´)´U´.
The final result of the transformation is a block of the form

scala
{ val q = ´p´
  val ´x_1´ = expr´_1´
  ...
  val ´x_l´ = expr´_k´
  val ´y_1´ = ´e_1´
  ...
  val ´y_m´ = ´e_m´
  val ´z_1´ = ´q.m\$default\$i[\mathit{targs}](\mathit{args}_1), ..., (\mathit{args}_l)´
  ...
  val ´z_d´ = ´q.m\$default\$j[\mathit{targs}](\mathit{args}_1), ..., (\mathit{args}_l)´
  q.´m´[´\mathit{targs}´](´\mathit{args}_1´), ..., (´\mathit{args}_l´)(´\mathit{args}´)
}

Signature Polymorphic Methods

For invocations of signature polymorphic methods of the target platform ´f´(´e_1, ..., e_m´), the invoked method has a different method type (´p_1´:´T_1, ..., p_n´:´T_n´)´U´ at each call site.
The parameter types ´T_, ..., T_n´ are the types of the argument expressions ´e_1, ..., e_m´.
If the declared return type ´R´ of the signature polymorphic method is any type other than scala.AnyRef, then the return type ´U´ is ´R´.
Otherwise, ´U´ is the expected type at the call site. If the expected type is undefined then ´U´ is scala.AnyRef.
The parameter names ´p_1, ..., p_n´ are fresh.

Note

On the Java platform version 11 and later, signature polymorphic methods are native, members of java.lang.invoke.MethodHandle or java.lang.invoke.VarHandle, and have a single repeated parameter of type java.lang.Object*.

Method Values

ebnf
SimpleExpr    ::=  SimpleExpr1 ‘_’

The expression ´e´ _ is well-formed if ´e´ is of method
type or if ´e´ is a call-by-name parameter.
If ´e´ is a method with parameters, ´e´ _ represents ´e´ converted to a function type by eta expansion.
If ´e´ is a parameterless method or call-by-name parameter of type => ´T´, ´e´ _ represents the function of type () => ´T´, which evaluates ´e´ when it is applied to the empty parameter list ().

Example

The method values in the left column are each equivalent to the eta-expanded expressions on the right.

placeholder syntax eta-expansion
math.sin _ x => math.sin(x)
math.pow _ (x1, x2) => math.pow(x1, x2)
val vs = 1 to 9; vs.fold _ (z) => (op) => vs.fold(z)(op)
(1 to 9).fold(z)_ { val eta1 = 1 to 9; val eta2 = z; op => eta1.fold(eta2)(op) }
Some(1).fold(??? : Int)_ { val eta1 = Some(1); val eta2 = () => ???; op => eta1.fold(eta2())(op) }

Note that a space is necessary between a method name and the trailing underscore because otherwise the underscore would be considered part of the name.

Type Applications

ebnf
SimpleExpr    ::=  SimpleExpr TypeArgs

A type application ´e´[´T_1, ..., T_n´] instantiates a polymorphic method ´e´ of type [´a_1´ >: ´L_1´ <: ´U_1, ..., a_n´ >: ´L_n´ <: ´U_n´]´S´ with argument types ´T_1, ..., T_n´.
Every argument type ´T_i´ must obey the corresponding bounds ´L_i´ and ´U_i´.
That is, for each ´i = 1, ..., n´, we must have ´\sigma L_i <: T_i <: \sigma U_i´, where ´\sigma´ is the substitution ´[a_1 := T_1, ..., a_n
:= T_n]´.
The type of the application is ´\sigma S´.

If ´e´ is not a method, and is instead of some value type, the type application is taken to be equivalent to ´e´.apply[´T_1 , ...,´ T´_n´], i.e. the application of an apply method defined by ´e´.

Type applications can be omitted if local type inference can infer best type parameters for a polymorphic method from the types of the actual method arguments and the expected result type.

Tuples

ebnf
SimpleExpr   ::=  ‘(’ [Exprs] ‘)’

A tuple expression (´e_1´, ..., ´e_n´) where ´n \geq 2´ is equivalent to the expression ´e_1´ *: ... *: ´e_n´ *: scala.EmptyTuple.

Note: as calls to *: are slow, a more efficient translation is free to be implemented. For example, (´e_1´, ´e_2´) could be translated to scala.Tuple2(´e_1´, ´e_2´), which is indeed equivalent to ´e_1´ *: ´e_2´ *: scala.EmptyTuple.

Notes:

  • The expression (´e_1´) is not equivalent to ´e_1´ *: scala.EmptyTuple, but instead a regular parenthesized expression.
  • The expression () is not an alias for scala.EmptyTuple, but instead the unique value of type scala.Unit.

Instance Creation Expressions

ebnf
SimpleExpr     ::=  ‘new’ (ClassTemplate | TemplateBody)

A simple instance creation expression is of the form new ´c´ where ´c´ is a constructor invocation.
Let ´T´ be the type of ´c´.
Then ´T´ must denote a (a type instance of) a non-abstract subclass of scala.AnyRef.
Furthermore, the concrete self type of the expression must conform to the self type of the class denoted by ´T´.
The concrete self type is normally ´T´, except if the expression new ´c´ appears as the right hand side of a value definition

scala
val ´x´: ´S´ = new ´c´

(where the type annotation : ´S´ may be missing).
In the latter case, the concrete self 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 initialized by 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´.
Such an expression is equivalent to the block

scala
{ class ´a´ extends ´t´; new ´a´ }

where ´a´ is a fresh name of an anonymous class which is inaccessible to user programs.

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 expression new AnyRef{´D´}.

Example

Consider the following structural instance creation expression:

scala
new { def getName() = "aaron" }

This is a shorthand for the general instance creation expression

scala
new AnyRef{ def getName() = "aaron" }

The latter is in turn a shorthand for the block

scala
{ class anon$X extends AnyRef{ def getName() = "aaron" }; new anon$X }

where anon$X is some freshly created name.

Blocks

ebnf
BlockExpr  ::=  ‘{’ CaseClauses ‘}’
             |  ‘{’ Block ‘}’
Block      ::=  BlockStat {semi BlockStat} [ResultExpr]

A block expression {´s_1´; ...; ´s_n´; ´e\,´} is constructed from a sequence of block statements ´s_1, ..., s_n´ and a final expression ´e´.
The statement sequence may not contain two definitions 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.
The expected type of all preceding statements is undefined.

The type of a block ´s_1´; ...; ´s_n´; ´e´ is some type ´T´ such that:

  • ´U <: T´ where ´U´ is the type of ´e´.
  • No value or type name is free in ´T´, i.e., ´T´ does not refer to any value or type locally defined in one of the statements ´s_1, ..., s_n´.
  • ´T´ is "as small as possible" (this is a soft requirement).

The precise way in which we compute ´T´, called type avoidance, is currently not defined in this specification.

Evaluation of the block entails evaluation of its statement sequence, followed by an evaluation of the final expression ´e´, which defines the result of the block.

A block expression {´c_1´; ...; ´c_n´} where ´c_1, ..., c_n´ are case clauses forms a pattern matching anonymous function.

Prefix, Infix, and Postfix Operations

ebnf
PostfixExpr     ::=  InfixExpr [id [nl]]
InfixExpr       ::=  PrefixExpr
                  |  InfixExpr id [nl] InfixExpr
PrefixExpr      ::=  [‘-’ | ‘+’ | ‘!’ | ‘~’] SimpleExpr

Expressions can be constructed from operands and operators.

Prefix Operations

A prefix operation ´\mathit{op};e´ consists of a prefix operator ´\mathit{op}´, which must be one of the identifiers ‘+’, ‘-’, ‘!’ or ‘~’, which must not be enclosed in backquotes.
The expression ´\mathit{op};e´ is equivalent to the postfix method application e.unary_´\mathit{op}´.

Prefix operators are different from normal method applications in that their operand expression need not be atomic.
For instance, the input sequence -sin(x) is read as -(sin(x)), whereas the method application negate sin(x) would be parsed as the application of the infix operator sin to the operands negate and (x).

Postfix Operations

A postfix operator can be an arbitrary identifier.
The postfix operation ´e;\mathit{op}´ is interpreted as ´e.\mathit{op}´.

Infix Operations

An 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.

scala
(all letters, as defined in [chapter 1](01-lexical-syntax.html), including `_` and `$`)
|
^
&
= !
< >
:
+ -
* / %
(other operator characters, as defined in [chapter 1](01-lexical-syntax.html), including Unicode categories `Sm` and `So`)

That is, operators starting with a letter have lowest precedence, followed by operators starting with ‘|’, etc.

There's one exception to this rule, which concerns assignment operators.
The precedence of an assignment operator is the same as the one of simple assignment (=).
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.
Operators 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 expression as follows.

  • 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 ´e_0; \mathit{op}_1; e_1; \mathit{op}_2 ... \mathit{op}_n; e_n´ with operators ´\mathit{op}_1, ..., \mathit{op}_n´ of the same precedence, then all these operators must have the same associativity.
    If all operators are left-associative, the sequence is interpreted as ´(...(e_0;\mathit{op}_1;e_1);\mathit{op}_2...);\mathit{op}_n;e_n´.
    Otherwise, if all operators are right-associative, the sequence is interpreted as ´e_0;\mathit{op}_1;(e_1;\mathit{op}_2;(... \mathit{op}_n;e_n)...)´.
  • Postfix operators always have lower precedence than infix operators. E.g. ´e_1;\mathit{op}_1;e_2;\mathit{op}_2´ is always equivalent to ´(e_1;\mathit{op}_1;e_2);\mathit{op}_2´.

The right-hand operand of a left-associative operator may consist of several arguments enclosed in parentheses, e.g. ´e;\mathit{op};(e_1,...,e_n)´.
This expression is then interpreted as ´e.\mathit{op}(e_1,...,e_n)´.

A left-associative binary operation ´e_1;\mathit{op};e_2´ is interpreted as ´e_1.\mathit{op}(e_2)´. If ´\mathit{op}´ is right-associative and its parameter is passed by name, the same operation is interpreted as ´e_2.\mathit{op}(e_1)´.
If ´\mathit{op}´ is right-associative and its parameter is passed by value, it is interpreted as { val ´x´=´e_1´; ´e_2´.´\mathit{op}´(´x\,´) }, where ´x´ is a fresh name.

Under -source:future, if the method name is alphanumeric and the target method is not marked infix, a deprecation warning is emitted.

Assignment Operators

An assignment operator is an operator symbol (syntax category op in Identifiers) that ends in an equals character “=”, with the following exceptions:

  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 assignments 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 operation which corresponds to the assignment

scala
´l´ = ´l´ + ´r´

except 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 be converted by an implicit conversion to a value with a member named +=.
  2. The assignment ´l´ = ´l´ + ´r´ is type-correct.
    In particular this implies that ´l´ refers to a variable or object that can be assigned to, and that is convertible to a value with a member named +.

Typed Expressions

ebnf
Expr1              ::=  PostfixExpr ‘:’ CompoundType

The typed expression ´e: T´ has type ´T´.
The type of expression ´e´ is expected to conform to ´T´.
The result of the expression is the value of ´e´ converted to type ´T´.

Example

Here are examples of well-typed and ill-typed expressions.

scala
1: Int               // legal, of type Int
1: Long              // legal, of type Long
// 1: string         // ***** illegal

Annotated Expressions

ebnf
Expr1              ::=  PostfixExpr ‘:’ Annotation {Annotation}

An annotated expression ´e´: @´a_1´ ... @´a_n´ attaches annotations ´a_1, ..., a_n´ to the expression ´e´.

Assignments

ebnf
Expr1        ::=  [SimpleExpr ‘.’] id ‘=’ Expr
               |  PrefixOperator SimpleExpr ‘=’ Expr
               |  SimpleExpr1 ArgumentExprs ‘=’ Expr

The interpretation of an assignment to a simple variable ´x´ = ´e´ depends on the definition of ´x´.
If ´x´ denotes a mutable variable, then the assignment changes the current 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 method defined in some template, and the same template contains a setter method ´x´_= as member, then the assignment ´x´ = ´e´ is interpreted as the invocation ´x´_=(´e\,´) of that setter method.
Analogously, an assignment ´f.x´ = ´e´ to a parameterless method ´x´ is interpreted as the invocation ´f.x´_=(´e\,´).
If ´x´ is an application of a unary operator, then the expression is interpreted as though it were written as the explicit application ´x´.unary_´\mathit{op}´, namely, as ´x´.unary_´\mathit{op}´_=(´e\,´).

An assignment ´f´(´\mathit{args}\,´) = ´e´ with a method application to the left of the ‘=’ operator is interpreted as ´f.´update(´\mathit{args}´, ´e\,´), i.e. the invocation of an update method defined by ´f´.

Example

Here are some assignment expressions and their equivalent expansions.

assignment expansion
x.f = e x.f_=(e)
x.f() = e x.f.update(e)
x.f(i) = e x.f.update(i, e)
x.f(i, j) = e x.f.update(i, j, e)

Example Imperative Matrix Multiplication

Here is the usual imperative code for matrix multiplication.

scala
def matmul(xss: Array[Array[Double]], yss: Array[Array[Double]]) = {
  val zss: Array[Array[Double]] = new Array(xss.length, yss(0).length)
  var i = 0
  while (i < xss.length) {
    var j = 0
    while (j < yss(0).length) {
      var acc = 0.0
      var k = 0
      while (k < yss.length) {
        acc = acc + xss(i)(k) * yss(k)(j)
        k += 1
      }
      zss(i)(j) = acc
      j += 1
    }
    i += 1
  }
  zss
}

Desugaring the array accesses and assignments yields the following expanded version:

scala
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 = 0
  while (i < xss.length) {
    var j = 0
    while (j < yss.apply(0).length) {
      var acc = 0.0
      var k = 0
      while (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
    }
    i += 1
  }
  zss
}

Conditional Expressions

ebnf
Expr1          ::=  ‘if’ ‘(’ Expr ‘)’ {nl} Expr [[semi] ‘else’ Expr]
                 |  ‘if‘ Expr ‘then‘ Expr [[semi] ‘else‘ Expr]

The conditional expression if (´e_1´) ´e_2´ else ´e_3´ chooses one of the values of ´e_2´ and ´e_3´, depending on the value of ´e_1´.
The condition ´e_1´ is expected to conform to type Boolean.
The then-part ´e_2´ and the else-part ´e_3´ are both expected to conform to the expected type of the conditional expression.
If there is no expected type, harmonization is attempted on ´e_2´ and ´e_3´.
The type of the conditional expression is the least upper bound of the types of ´e_2´ and ´e_3´ after harmonization.
A semicolon preceding the else symbol of a conditional expression is ignored.

The conditional expression is evaluated by evaluating first ´e_1´.
If this evaluates to true, the result of evaluating ´e_2´ is returned, otherwise the result of evaluating ´e_3´ is returned.

A short form of the conditional expression eliminates the else-part.
The conditional expression if (´e_1´) ´e_2´ is evaluated as if it was if (´e_1´) ´e_2´ else ().

While Loop Expressions

ebnf
Expr1          ::=  ‘while’ ‘(’ Expr ‘)’ {nl} Expr
                 |  ‘while’ Expr ‘do’ Expr

The while loop expression while (´e_1´) ´e_2´ is typed and evaluated as if it was an application of whileLoop (´e_1´) (´e_2´) where the hypothetical method whileLoop is defined as follows.

scala
def whileLoop(cond: => Boolean)(body: => Unit): Unit  =
  if (cond) { body ; whileLoop(cond)(body) } else {}

For Comprehensions and For Loops

ebnf
Expr1          ::=  ‘for’ (‘(’ Enumerators ‘)’ | ‘{’ Enumerators ‘}’)
                       {nl} [‘yield’] Expr
Enumerators    ::=  Generator {semi Generator}
Generator      ::=  [‘case’] Pattern1 ‘<-’ Expr {[semi] Guard | semi Pattern1 ‘=’ Expr}
Guard          ::=  ‘if’ PostfixExpr

A for loop for (´\mathit{enums}\,´) ´e´ executes expression ´e´ for each binding generated by the enumerators ´\mathit{enums}´.
A for comprehension for (´\mathit{enums}\,´) yield ´e´ evaluates expression ´e´ for each binding generated by the enumerators ´\mathit{enums}´ and collects the results.
An enumerator sequence always starts with a generator; this can be followed by further generators, value definitions, or guards.

A generator ´p´ <- ´e´ produces bindings from an expression ´e´ which is deconstructed by the pattern ´p´.
The pattern must be irrefutable.
A conditional generator case ´p´ <- ´e´ tests whether elements produced by ´e´ match the pattern and discards the ones that do not match.

A value definition ´p´ = ´e´ binds the value name ´p´ (or several names in a pattern ´p´) to the result of evaluating the expression ´e´.
A guard if ´e´ contains a boolean 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 different ways for different carrier types.

The translation scheme is as follows.
In a first step, every generator case ´p´ <- ´e´ is replaced by

scala
´p´ <- ´e´.withFilter { case ´p´ => true; case _ => false }

Then, the following rules are applied repeatedly until all comprehensions have been eliminated.

  • A for comprehension for (´p´ <- ´e\,´) yield ´e'´ is translated to ´e´.map { case ´p´ => ´e'´ }.

  • A for loop for (´p´ <- ´e\,´) ´e'´ is translated to ´e´.foreach { case ´p´ => ´e'´ }.

  • A for comprehension

    scala
    for (´p´ <- ´e´; ´p'´ <- ´e'; ...´) yield ´e''´

    where ... is a (possibly empty) sequence of generators, definitions, or guards, is translated to

    scala
    ´e´.flatMap { case ´p´ => for (´p'´ <- ´e'; ...´) yield ´e''´ }
  • A for loop

    scala
    for (´p´ <- ´e´; ´p'´ <- ´e'; ...´) ´e''´

    where ... is a (possibly empty) sequence of generators, definitions, or guards, is translated to

    scala
    ´e´.foreach { case ´p´ => for (´p'´ <- ´e'; ...´) ´e''´ }
  • A generator ´p´ <- ´e´ followed by a guard if ´g´ is translated to a single generator ´p´ <- ´e´.withFilter({ case ´p´ => ´g\,´ }).

  • A generator ´p´ <- ´e´ followed by a value definition ´p'´ = ´e'´ is translated to the following generator of pairs of values, where ´x´ and ´x'´ are fresh names:

    scala
    (´p´, ´p'´) <- for (´x @ p´ <- ´e´) yield { val ´x' @ p'´ = ´e'´; (´x´, ´x'´) }

Example

The following code produces all pairs of numbers between ´1´ and ´n-1´ whose sums are prime.

scala
for  { i <- 1 until n
       j <- 1 until i
       if isPrime(i+j)
} yield (i, j)

The for comprehension is translated to:

scala
(1 until n)
  .flatMap {
     case i => (1 until i)
       .withFilter { j => isPrime(i+j) }
       .map { case j => (i, j) } }

Example

For comprehensions can be used to express vector and matrix algorithms concisely.
For instance, here is a method to compute the transpose of a given matrix:

scala
def transpose[A](xss: Array[Array[A]]) = {
  for (i <- Array.range(0, xss(0).length)) yield
    for (xs <- xss) yield xs(i)
}

Here is a method to compute the scalar product of two vectors:

scala
def scalprod(xs: Array[Double], ys: Array[Double]) = {
  var acc = 0.0
  for ((x, y) <- xs zip ys) acc = acc + x * y
  acc
}

Finally, here is a method to compute the product of two matrices.
Compare with the imperative version.

scala
def matmul(xss: Array[Array[Double]], yss: Array[Array[Double]]) = {
  val ysst = transpose(yss)
  for (xs <- xss) yield
    for (yst <- ysst) yield
      scalprod(xs, yst)
}

The code above makes use of the fact that map, flatMap, withFilter, and foreach are defined for instances of class scala.Array.

Return Expressions

ebnf
Expr1      ::=  ‘return’ [Expr]

A return expression return ´e´ must occur inside the body of some enclosing user defined method.
The innermost enclosing method in a source program, ´m´, must have an explicitly declared result type, and the type of ´e´ must conform to it.

The return expression evaluates the expression ´e´ and returns its value as the result of ´m´.
The evaluation of any statements or expressions following the 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 were return ().

Non-Local Returns (deprecated)

Returning from a method from within a nested function is deprecated.

It is implemented by throwing and catching a scala.runtime.NonLocalReturnControl.
Any exception catches between the point of return and the enclosing methods might see and catch that exception.
A key comparison makes sure that this exception is 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 that the enclosing method ´m´ has already returned before the return expression is executed.
In that case, the thrown scala.runtime.NonLocalReturnControl will not be caught, and will propagate up the call stack.

Throw Expressions

ebnf
Expr1      ::=  ‘throw’ Expr

A throw expression throw ´e´ evaluates the expression ´e´.
The type of this expression must conform to Throwable.
If ´e´ evaluates to an exception reference, evaluation is aborted with the thrown exception.
If ´e´ evaluates to null, evaluation is instead aborted with a NullPointerException.
If there is an active try expression which handles the thrown exception, evaluation resumes with the handler; otherwise the thread executing the throw is aborted.
The type of a throw expression is scala.Nothing.

Try Expressions

ebnf
Expr1    ::=  ‘try’ Expr [Catches] [‘finally’ Expr]

Catches  ::=  ‘catch‘ (Expr | ExprCaseClause)

A try expression is of the form try ´b´ catch ´h´ where the handler ´h´ is usually a pattern matching anonymous function

scala
{ case ´p_1´ => ´b_1´ ... case ´p_n´ => ´b_n´ }

If the handler is a single ExprCaseClause, it is a shorthand for that ExprCaseClause wrapped in a pattern matching anonymous function.

This expression is evaluated by evaluating the block ´b´.
If evaluation of ´b´ does not cause an exception to be thrown, the result of ´b´ is returned.
Otherwise the handler ´h´ 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 case matching the thrown exception, the exception is re-thrown.
More generally, if the handler is a PartialFunction, it is applied only if it is defined at the given exception.

Let ´\mathit{pt}´ be the expected type of the try expression.
The expression ´b´ is expected to conform to ´\mathit{pt}´.
The handler ´h´ is expected conform to type scala.Function[scala.Throwable, ´\mathit{pt}\,´].
The type of the try expression is the least upper bound of the type of ´b´ and the result type of ´h´.

A try expression try ´b´ finally ´e´ evaluates the expression ´b´.
If evaluation of ´b´ does not cause an exception to be thrown, the expression ´e´ is evaluated.
If an exception is thrown during evaluation of ´e´, the evaluation of the try expression is aborted with 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 evaluated.
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 during evaluation of ´e´, the original exception thrown in ´b´ is re-thrown once evaluation of ´e´ has completed.
The expression ´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 expression try ´b´ catch ´e_1´ finally ´e_2´ is a shorthand for try { try ´b´ catch ´e_1´ } finally ´e_2´.

Anonymous Functions

ebnf
Expr            ::=  (Bindings | [‘implicit’] id | ‘_’) ‘=>’ Expr
ResultExpr      ::=  (Bindings | ([‘implicit’] id | ‘_’) ‘:’ CompoundType) ‘=>’ Block
Bindings        ::=  ‘(’ Binding {‘,’ Binding} ‘)’
Binding         ::=  (id | ‘_’) [‘:’ Type]

The anonymous function of arity ´n´, (´x_1´: ´T_1, ..., x_n´: ´T_n´) => e maps parameters ´x_i´ of types ´T_i´ to a result given by expression ´e´.
The scope of each formal parameter ´x_i´ is ´e´.
Formal parameters must have pairwise distinct names.
Type bindings can be omitted, in which case the compiler will attempt to infer valid bindings.

Note: () => ´e´ defines a nullary function (´n´ = 0), and not for example (_: Unit) => ´e´.

In the case of a single untyped formal parameter, (´x\,´) => ´e´ can be abbreviated to ´x´ => ´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.

A formal parameter may also be a wildcard represented by an underscore _.
In that case, 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; however the parameter section itself does not count as an implicit parameter section.
Hence, arguments to anonymous functions always have to be given explicitly.

Translation

If the expected type of the anonymous function is of the shape scala.Function´n´[´S_1´, ..., ´S_n´, ´R\,´], or can be SAM-converted to such a function type, the type ´T_i´ of a parameter ´x_i´ can be omitted, as far as ´S_i´ is defined in the expected type, and ´T_i´ = ´S_i´ is assumed.
Furthermore, the expected type when type checking ´e´ is ´R´.

If there is no expected type for the function literal, all formal parameter types ´T_i´ must be specified explicitly, and the expected type of ´e´ is undefined.
The type of the anonymous function is scala.Function´n´[´T_1´, ..., ´T_n´, ´R\,´], where ´R´ is the packed type of ´e´.
´R´ must be equivalent to a type which does not refer to any of the formal parameters ´x_i´.

The eventual run-time value of an anonymous function is determined by the expected type:

  • a subclass of one of the builtin function types, scala.Function´n´[´S_1, ..., S_n´, ´R\,´] (with ´S_i´ and ´R´ fully defined),
  • a single-abstract-method (SAM) type;
  • PartialFunction[´T´, ´U´]
  • some other type.

The standard anonymous function evaluates in the same way as the following instance creation expression:

scala
new scala.Function´n´[´T_1, ..., T_n´, ´T´] {
  def apply(´x_1´: ´T_1, ..., x_n´: ´T_n´): ´T´ = ´e´
}

The same evaluation holds for a SAM type, except that the instantiated type is given by the SAM type, and the implemented method is the single abstract method member of this type.

The underlying platform may provide more efficient ways of constructing these instances, such as Java 8's invokedynamic bytecode and LambdaMetaFactory class.

When a PartialFunction is required, an additional member isDefinedAt is synthesized, which simply returns true.
However, if the function literal has the shape x => x match { $...$ }, then isDefinedAt is derived from the pattern match in the following way: each case from the match expression evaluates to true, and if there is no default case, a default case is added that evaluates to false.
For more details on how that is implemented see "Pattern Matching Anonymous Functions".

Example

Examples of anonymous functions:

scala
x => x                             // The identity function

f => 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 Functions

ebnf
SimpleExpr1  ::=  ‘_’

An expression (of syntactic category Expr) may contain embedded underscore symbols _ at places where identifiers are legal.
Such an expression represents an anonymous function where subsequent occurrences of underscores denote successive parameters.

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 following two conditions hold: (1) ´e´ properly contains ´u´, and (2) there is no other expression of syntactic category Expr which is properly contained in ´e´ and which itself properly contains ´u´.

If an expression ´e´ binds underscore sections ´u_1, ..., u_n´, in this order, it is equivalent to the anonymous function (´u'_1´, ... ´u'_n´) => ´e'´ where each ´u_i'´ results from ´u_i´ by replacing the underscore with a fresh identifier and ´e'´ results from ´e´ by replacing each underscore section ´u_i´ by ´u_i'´.

Example

The anonymous functions in the left column use placeholder syntax.
Each of these is equivalent to the anonymous function on its right.

_ + 1 x => x + 1
_ * _ (x1, x2) => x1 * x2
(_: Int) * 2 (x: Int) => (x: Int) * 2
if (_) x else y z => if (z) x else y
_.map(f) x => x.map(f)
_.map(_ + 1) x => x.map(y => y + 1)

Constant Expressions

Constant expressions are expressions that the Scala compiler can evaluate to a constant.
The definition of "constant expression" depends on the platform, but they include 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
  • An element of an enumeration from the underlying platform
  • A literal array, of the form Array´(c_1, ..., c_n)´, where all of the ´c_i´'s are themselves constant expressions
  • An identifier defined by a constant value definition.

Statements

ebnf
BlockStat    ::=  Import
               |  {Annotation} [‘implicit’] [‘lazy’] Def
               |  {Annotation} {LocalModifier} TmplDef
               |  Expr1
               |
TemplateStat ::=  Import
               |  {Annotation} {Modifier} Def
               |  {Annotation} {Modifier} Dcl
               |  Expr
               |

Statements occur as parts of blocks and templates.
A statement can be an import, a definition or an expression, or it can be empty.
An expression that is used as a statement 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 only modifier 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 order they are written.

Harmonization

Harmonization of a list of expressions tries to adapt Int literals to match the types of sibling trees.
For example, when writing

scala
scala.collection.mutable.ArrayBuffer(5.4, 6, 6.4)

the inferred element type would be AnyVal without harmonization.
Harmonization turns the integer literal 6 into the double literal 6.0 so that the element type becomes Double.

Formally, given a list of expressions ´e_1, ..., e_n´ with types ´T_1, ..., T_n´, harmonization behaves as follows:

  1. If there is an expected type, return the original list.
  2. Otherwise, if there exists ´T_i´ that is not a primitive numeric type (Char, Byte, Short, Int, Long, Float, Double), return the original list.
  3. Otherwise,
    1. Partition the ´e_i´ into the integer literals ´f_j´ and the other expressions ´g_k´.
    2. If all the ´g_k´ have the same numeric type ´T´, possibly after widening, and if all the integer literals ´f_j´ can be converted without loss of precision to ´T´, return the list of ´e_i´ where every int literal is converted to ´T´.
    3. Otherwise, return the original list.

Harmonization is used in conditional expressions and pattern matches, as well as in local type inference.

Implicit Conversions

Implicit conversions can be applied to expressions whose type does not match their expected type, to qualifiers in selections, and to unapplied methods.
The available implicit conversions are given in the next two sub-sections.

Value Conversions

The following seven implicit conversions can be applied to an expression ´e´ which has some value type ´T´ and which is type-checked with some expected type ´\mathit{pt}´.

Static Overloading Resolution

If an expression denotes several possible members of a class, overloading resolution is applied to pick a unique member.

Type Instantiation

An expression ´e´ of polymorphic type

scala
[´a_1´ >: ´L_1´ <: ´U_1, ..., a_n´ >: ´L_n´ <: ´U_n´]´T´

which does not appear as the function part of a type application is converted to a type instance of ´T´ by determining with local type inference instance types ´T_1, ..., T_n´ for the type variables ´a_1, ..., a_n´ and implicitly embedding ´e´ in the type application ´e´[´T_1, ..., T_n´].

Numeric Literal Conversion

If the expected type is Byte, Short, Long or Char, and the expression ´e´ is an Int literal fitting in the range of that type, it is converted to the same literal in that type.

Likewise, if the expected type is Float or Double, and the expression ´e´ is a numeric literal (of any type) 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 converted to the expected type by embedding it in the term { ´e´; () }.

SAM conversion

An expression (p1, ..., pN) => body of function type (T1, ..., TN) => T is sam-convertible to the expected type S if the following holds:

  • the class C of S declares an abstract method m with signature (p1: A1, ..., pN: AN): R;
  • besides m, C must not declare or inherit any other deferred value members;
  • the method m must have a single argument list;
  • there must be a type U that is a subtype of S, so that the expression new U { final def m(p1: A1, ..., pN: AN): R = body } is well-typed (conforming to the expected type S);
  • for the purpose of scoping, m should be considered a static member (U's members are not in scope in body);
  • (A1, ..., AN) => R is a subtype of (T1, ..., TN) => T (satisfying this condition drives type inference of unknown type parameters in S);

Note that a function literal that targets a SAM is not necessarily compiled to the above instance creation expression.
This is platform-dependent.

It follows that:

  • if class C defines a constructor, it must be accessible and must define exactly one, empty, argument list;
  • class C cannot be final or sealed (for simplicity we ignore the possibility of SAM conversion in the same compilation unit as the sealed class);
  • m cannot be polymorphic;
  • it must be possible to derive a fully-defined type U from S by inferring any unknown type parameters of C.

Finally, we impose some implementation restrictions (these may be lifted in future releases):

  • C must not be nested or local (it must not capture its environment, as that results in a nonzero-argument constructor)
  • C's constructor must not have an implicit argument list (this simplifies type inference);
  • C must not declare a self type (this simplifies type inference);
  • C must not be @specialized.

View Application

If none of the previous conversions applies, and ´e´'s type does not conform to the expected type ´\mathit{pt}´, it is attempted to convert ´e´ to the expected type with a view.

Selection on `Dynamic`

If none of the previous conversions applies, and ´e´ is a prefix of a selection ´e.x´, and ´e´'s type conforms to class scala.Dynamic, then the selection is rewritten according to the rules for dynamic member selection.

Method Conversions

The following four implicit conversions can be applied to methods which are not applied 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 arguments are passed following the rules here.

Eta Expansion

Otherwise, if the method is not a constructor, and the expected type ´\mathit{pt}´ is a function type, or, for methods of non-zero arity, a type sam-convertible to a function type, ´(\mathit{Ts}') \Rightarrow T'´, eta-expansion is performed on the expression ´e´.

(The exception for zero-arity methods is to avoid surprises due to unexpected sam conversion.)

Empty Application

Otherwise, if ´e´ has method type ´()T´, it is implicitly applied to the empty argument list, yielding ´e()´.

Overloading Resolution

If 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 on whether or not ´e´ is used as a method.
Let ´\mathscr{A}´ be the set of members referenced by ´e´.

Assume first that ´e´ appears as a function in an application, as in ´e´(´e_1´, ..., ´e_m´).

One first determines the set of methods that are potentially applicable based on the shape of the arguments.

The shape of an argument expression ´e´, written ´\mathit{shape}(e)´, is a type that is defined as follows:

  • For a function expression (´p_1´: ´T_1, ..., p_n´: ´T_n´) => ´b´: (Any, ..., Any) => ´\mathit{shape}(b)´, where Any occurs ´n´ times in the argument type.
  • For a pattern-matching anonymous function definition { case ... }: PartialFunction[Any, Nothing].
  • For a named argument ´n´ = ´e´: ´\mathit{shape}(e)´.
  • For all other expressions: Nothing.

Let ´\mathscr{B}´ be the set of alternatives in ´\mathscr{A}´ that are applicable to expressions ´(e_1, ..., e_n)´ of types ´(\mathit{shape}(e_1), ..., \mathit{shape}(e_n))´.
If there is precisely one alternative in ´\mathscr{B}´, that alternative is chosen.

Otherwise, let ´S_1, ..., S_m´ be the list of types obtained by typing each argument as follows.

Normally, an argument is typed without an expected type, except when all alternatives explicitly specify the same parameter type for this argument (a missing parameter type, due to e.g. arity differences, is taken as NoType, thus resorting to no expected type), or when trying to propagate more type information to aid inference of higher-order function parameter types, as explained next.

The intuition for higher-order function parameter type inference is that all arguments must be of a function-like type (PartialFunction, FunctionN or some equivalent SAM type), which in turn must define the same set of higher-order argument types, so that they can safely be used as the expected type of a given argument of the overloaded method, without unduly ruling out any alternatives.
The intent is not to steer overloading resolution, but to preserve enough type information to steer type inference of the arguments (a function literal or eta-expanded method) to this overloaded method.

Note that the expected type drives eta-expansion (not performed unless a function-like type is expected), as well as inference of omitted parameter types of function literals.

More precisely, an argument ´e_i´ is typed with an expected type that is derived from the ´i´th argument type found in each alternative (call these ´T_{ij}´ for alternative ´j´ and argument position ´i´) when all ´T_{ij}´ are function types ´(A_{1j},..., A_{nj}) => ?´ (or the equivalent PartialFunction, or SAM) of some arity ´n´, and their argument types ´A_{kj}´ are identical across all overloads ´j´ for a given ´k´.
Then, the expected type for ´e_i´ is derived as follows:

  • we use ´PartialFunction[A_{1j},..., A_{nj}, ?]´ if for some overload ´j´, ´T_{ij}´'s type symbol is PartialFunction;
  • else, if for some ´j´, ´T_{ij}´ is FunctionN, the expected type is ´FunctionN[A_{1j},..., A_{nj}, ?]´;
  • else, if for all ´j´, ´T_{ij}´ is a SAM type of the same class, defining argument types ´A_{1j},..., A_{nj}´ (and a potentially varying result type), the expected type encodes these argument types and the SAM class.

For every member ´m´ in ´\mathscr{B}´ one determines whether it is applicable to expressions (´e_1, ..., e_m´) of types ´S_1, ..., S_m´.

It is an error if none of the members in ´\mathscr{B}´ is applicable.
If there is one single applicable alternative, that alternative is chosen.
Otherwise, let ´\mathscr{CC}´ be the set of applicable alternatives which don't employ any default argument in the application to ´e_1, ..., e_m´.

It is again an error if ´\mathscr{CC}´ is empty.
Otherwise, one chooses the most specific alternative among the alternatives in ´\mathscr{CC}´, according to the following definition of being "as specific as", and "more specific than":

  • A parameterized method ´m´ of type (´p_1:T_1, ..., p_n:T_n´)´U´ is as specific as some other member ´m'´ of type ´S´ if ´m'´ is applicable to arguments (´p_1, ..., p_n´) of types ´T_1, ..., T_n´.
    If the last parameter ´p_n´ has a vararg type ´T*´, then m must be applicable to arbitrary numbers of ´T´ parameters (which implies that it must be a varargs method as well).
  • A polymorphic method of type [´a_1´ >: ´L_1´ <: ´U_1, ..., a_n´ >: ´L_n´ <: ´U_n´]´T´ is as specific as some other member ´m'´ of type ´S´ if ´T´ is as specific as ´S´ under the assumption that for ´i = 1, ..., n´ each ´a_i´ is an abstract type name bounded from below by ´L_i´ and from above by ´U_i´.
  • A member of any other type ´T´ is:
    • always as specific as a parameterized method or a polymorphic method.
    • as specific as a member ´m'´ of any other type ´S´ if ´T´ is compatible with ´S´.

The 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 object defining ´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 ´\mathscr{CC}´ which is more specific than all other alternatives in ´\mathscr{CC}´.

Assume next that ´e´ appears as a method in a type application, as in ´e´[´\mathit{targs}\,´].
Then all alternatives in ´\mathscr{A}´ which take the same number of type parameters as there are type arguments in ´\mathit{targs}´ are chosen.
It is an error if no such alternative exists.
If there are several such alternatives, overloading resolution is applied again to the whole expression ´e´[´\mathit{targs}\,´].

Assume finally that ´e´ does not appear as a method in either an application or a type application.
If an expected type is given, let ´\mathscr{B}´ be the set of those alternatives in ´\mathscr{A}´ which are compatible to it.
Otherwise, let ´\mathscr{B}´ be the same as ´\mathscr{A}´.
In this last case we choose the most specific alternative among all alternatives in ´\mathscr{B}´.
It is an error if there is no alternative in ´\mathscr{B}´ which is more specific than all other alternatives in ´\mathscr{B}´.

Example

Consider the following definitions:

scala
class A extends B {}
def f(x: B, y: B) = ...
def f(x: A, y: B) = ...
val a: A
val b: B

Then the application f(b, b) refers to the first definition of ´f´ whereas the application f(a, a) refers to the second.
Assume now we add a third overloaded definition

scala
def f(x: B, y: A) = ...

Then the application f(a, a) is rejected for being ambiguous, since no most specific applicable signature exists.

Local Type Inference

Local type inference infers type arguments to be passed to expressions of polymorphic type.
Say ´e´ is of type [´a_1´ >: ´L_1´ <: ´U_1, ..., a_n´ >: ´L_n´ <: ´U_n´]´T´ and no explicit type parameters are given.

Local type inference converts this expression to a type application ´e´[´T_1, ..., T_n´].
The choice of the type arguments ´T_1, ..., T_n´ depends on the context in which the expression appears and on the expected type ´\mathit{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.x´ has type ´S´, it is now treated as having type [´a_1´ >: ´L_1´ <: ´U_1, ..., a_n´ >: ´L_n´ <: ´U_n´]´S´, and local type inference is applied in turn to infer type arguments for ´a_1, ..., a_n´, using the context in which ´e.x´ appears.

Case 2: Values

If the expression ´e´ appears as a value without being applied to value arguments, the type arguments are inferred by solving a constraint system which relates the expression's type ´T´ with the expected type ´\mathit{pt}´.
Without loss of generality we can assume that ´T´ is a value type; if it is a method type we apply eta-expansion to convert it to a function type.
Solving means finding a substitution ´\sigma´ of types ´T_i´ for the type parameters ´a_i´ such that

  • None of the inferred types ´T_i´ is a singleton type unless it is a singleton type corresponding to an object or a constant value definition or the corresponding bound ´U_i´ is a subtype of scala.Singleton.
  • All type parameter bounds are respected, i.e. ´\sigma L_i <: \sigma a_i´ and ´\sigma a_i <: \sigma U_i´ for ´i = 1, ..., n´.
  • The expression's type conforms to the expected type, i.e. ´\sigma T <: \sigma \mathit{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 ´a_i´ a minimal or maximal type ´T_i´ of the solution space.
A maximal type ´T_i´ will be chosen if the type parameter ´a_i´ appears contravariantly in the type ´T´ of the expression.
A minimal type ´T_i´ will 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 solution of the given constraint system for the type ´T´.

Case 3: Methods

The last case applies if the expression ´e´ appears in an application ´e(d_1, ..., d_m)´.
In that case ´T´ is a method type ´(p_1:R_1, ..., p_m:R_m)T'´.
Without loss of generality we can assume that the result type ´T'´ is a value type; if it is a method type we apply eta-expansion to
convert it to a function type.
One computes first the types ´S_j´ of the argument expressions ´d_j´, using two alternative schemes.
Each argument expression ´d_j´ is typed first with the expected type ´R_j´, in which the type parameters ´a_1, ..., a_n´ are taken as type constants.
If this fails, the argument ´d_j´ is typed instead with an expected type ´R_j'´ which results from ´R_j´ by replacing every type parameter in ´a_1, ..., a_n´ with undefined.

In a second step, type arguments are inferred by solving a constraint system which relates the method's type with the expected type ´\mathit{pt}´ and the argument types ´S_1, ..., S_m´.
Solving the constraint system means finding a substitution ´\sigma´ of types ´T_i´ for the type parameters ´a_i´ such that

  • None of the inferred types ´T_i´ is a singleton type unless it is a singleton type corresponding to an object or a constant value definition or the corresponding bound ´U_i´ is a subtype of scala.Singleton.
  • All type parameter bounds are respected, i.e. ´\sigma L_i <: \sigma a_i´ and ´\sigma a_i <: \sigma U_i´ for ´i = 1, ..., n´.
  • The method's result type ´T'´ conforms to the expected type, i.e. ´\sigma T' <: \sigma \mathit{pt}´.
  • Each argument type weakly conforms to the corresponding formal parameter type, i.e. ´\sigma S_j <:_w \sigma R_j´ for ´j = 1, ..., m´.

It is a compile time error if no such substitution exists.
If several solutions exist, an optimal one for the type ´T'´ is chosen.

All or parts of an expected type ´\mathit{pt}´ may be undefined.
The rules for conformance are extended to this case by adding the rule that for any type ´T´ the following two statements are always true: ´\mathit{undefined} <: T´ and ´T <: \mathit{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 a solution set has several optimal solutions for a type.
In that case, a Scala compiler is free to pick any one of them.

Example

Consider the two methods:

scala
def cons[A](x: A, xs: List[A]): List[A] = x :: xs
def nil[B]: List[B] = Nil

and the definition

scala
val 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 the following 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-check nil with an expected type List[a].
This leads to the constraint system

scala
List[b?] <: List[a]

where we have labeled b? with a question mark to indicate that it is a variable in the constraint system.
Because class List is covariant, the optimal solution of this constraint is

scala
b = scala.Nothing

In a second step, one solves the following constraint system for the type parameter a of cons:

scala
Int <: a?
List[scala.Nothing] <: List[a?]
List[a?] <: ´\mathit{undefined}´

The optimal solution of this constraint system is

scala
a = Int

so Int is the type inferred for a.

Example

Consider now the definition

scala
val ys = cons("abc", xs)

where xs is defined of type List[Int] as before.
In this case local type inference proceeds 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 type List[a].
This fails,as List[Int] is not a subtype of List[a].
Therefore, the second strategy is tried; xs is now typed with expected type List[´\mathit{undefined}´].
This succeeds and yields the argument type List[Int].

In a second step, one solves the following constraint system for the type parameter a of cons:

scala
String <: a?
List[Int] <: List[a?]
List[a?] <: ´\mathit{undefined}´

The optimal solution of this constraint system is

scala
a = scala.Any

so scala.Any is the type inferred for a.

Eta Expansion

Eta-expansion converts an expression of method type to an equivalent expression of function type.
It proceeds in two steps.

First, one identifies the maximal sub-expressions of ´e´; let's say these are ´e_1, ..., e_m´.
For each of these, one creates a fresh name ´x_i´.
Let ´e'´ be the expression resulting from replacing every maximal subexpression ´e_i´ in ´e´ by the corresponding fresh name ´x_i´.
Second, one creates a fresh name ´y_i´ for every argument type ´T_i´ of the method (´i = 1 , ..., n´).
The result of eta-conversion is then:

scala
{ val ´x_1´ = ´e_1´;
  ...
  val ´x_m´ = ´e_m´;
  (´y_1: T_1, ..., y_n: T_n´) => ´e'´(´y_1, ..., y_n´)
}

The behavior of call-by-name parameters is preserved under eta-expansion: the corresponding actual argument expression, a sub-expression of parameterless method type, is not evaluated in the expanded block.

Dynamic Member Selection

The standard Scala library defines a marker trait scala.Dynamic.
Subclasses of this trait are able to intercept selections and applications on their instances by defining methods of the names applyDynamic, applyDynamicNamed, selectDynamic, and updateDynamic.

The following rewrites are performed, assuming ´e´'s type conforms to scala.Dynamic, and the original expression does not type check under the normal rules, as specified fully in the relevant subsection of implicit conversion:

  • e.m[Ti](xi) becomes e.applyDynamic[Ti]("m")(xi)
  • e.m[Ti] becomes e.selectDynamic[Ti]("m")
  • e.m = x becomes e.updateDynamic("m")(x)

If any arguments are named in the application (one of the xi is of the shape arg = x), their name is preserved as the first component of the pair passed to applyDynamicNamed (for missing names, "" is used):

  • e.m[Ti](argi = xi) becomes e.applyDynamicNamed[Ti]("m")(("argi", xi))

Finally:

  • e.m(x) = y becomes e.selectDynamic("m").update(x, y)

None of these methods are actually defined in the scala.Dynamic, so that users are free to define them with or without type parameters, or implicit arguments.


Spec 07 Implicits (`docs/_spec/07-implicits.md`)


title: Implicits layout: default chapter: 7

Implicits

The Implicit Modifier

ebnf
LocalModifier  ::= ‘implicit’
ParamClauses   ::= {ParamClause} [nl] ‘(’ ‘implicit’ Params ‘)’

Template members and parameters labeled with an implicit modifier can be passed to implicit parameters and can be used as implicit conversions called views.
The implicit modifier is illegal for all type members, as well as for top-level objects.

Example Monoid

The following code defines an abstract class of monoids and two concrete implementations, StringMonoid and IntMonoid.
The two implementations are marked implicit.

scala
abstract class Monoid[A] extends SemiGroup[A] {
  def unit: A
  def 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 + y
    def unit: Int = 0
  }
}

Implicit Parameters

An implicit parameter list (implicit ´p_1´,...,´p_n´) of a method marks the parameters ´p_1, ..., p_n´ 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 normal method.
In this case the implicit label has no effect.
However, if such a method misses arguments for its implicit parameters, such arguments will be automatically provided.

The actual arguments that are eligible to be passed to an implicit parameter of type ´T´ 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 or an implicit parameter.
To be accessible without a prefix, an identifier must be a local name, a member of an enclosing template or a name introduced by an import clause.
If there are no eligible identifiers under this rule, then, second, eligible are also all implicit members of some object that belongs to the implicit scope of the implicit parameter's type, ´T´.

The implicit scope of a type ´T´ consists of all companion modules of classes that are associated with the implicit parameter's type.
Here, we say a class ´C´ is associated with a type ´T´ if it is a base class of some part of ´T´.

The parts of a type ´T´ are:

  • if ´T´ is a compound type ´T_1´ with ... with ´T_n´, the union of the parts of ´T_1, ..., T_n´, as well as ´T´ itself;
  • if ´T´ is a parameterized type ´S´[´T_1, ..., T_n´], the union of the parts of ´S´ and ´T_1, ..., T_n´;
  • 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;
  • if ´T´ is a type alias, the parts of its expansion;
  • if ´T´ is an abstract type, the parts of its upper bound;
  • if ´T´ is a structural type with a method with argument types ´T_1, ..., T_n´ and result type ´U´, the union of the parts of ´T_1, ..., T_n´ and ´U´;
  • in all other cases, just ´T´ itself.

Note that packages are internally represented as classes with companion modules to hold the package members.
Thus, implicits defined in a package object are part of the implicit scope of a type prefixed by that package.

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.
If the parameter has a default argument and no implicit argument can be found the default argument is used.

Example

Assuming the classes from the Monoid example, here is a method which computes the sum of a list of elements using the monoid's add and unit operations.

scala
def sum[A](xs: List[A])(implicit m: Monoid[A]): A =
  if (xs.isEmpty) m.unit
  else m.add(xs.head, sum(xs.tail))

The monoid in question is marked as an implicit parameter, and can therefore be inferred 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 formal type parameter a of sum needs to be instantiated to Int.
The only eligible object which 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 arguments are inferred.

Implicit methods can themselves have implicit parameters.
An example is the following method from module scala.List, which injects lists into the scala.Ordered class, provided the element type of the list is also convertible to this type.

scala
implicit def list2ordered[A](x: List[A])
  (implicit elem2ordered: A => Ordered[A]): Ordered[List[A]] =
  ...

Assume in addition a method

scala
implicit def int2ordered(x: Int): Ordered[Int]

that injects integers into the Ordered class.
We can now define a sort method over ordered lists:

scala
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:

scala
sort(yss)

The call above will be completed by passing two nested implicit arguments:

scala
sort(yss)((xs: List[Int]) => list2ordered[Int](xs)(int2ordered))

The possibility of passing implicit arguments to implicit arguments raises the possibility of an infinite recursion.
For instance, one might try to define the following method, which injects every type into the Ordered class:

scala
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 another injection into the Ordered class, one would obtain an infinite expansion:

scala
sort(arg)(x => magic(x)(x => magic(x)(x => ... )))

Such infinite expansions should be detected and reported as errors, however to support the deliberate implicit construction of recursive values we allow implicit arguments to be marked as by-name.
At call sites recursive uses of implicit values are permitted if they occur in an implicit by-name argument.

Consider the following example,

scala
trait Foo {
  def next: Foo
}

object Foo {
  implicit def foo(implicit rec: Foo): Foo =
    new Foo { def next = rec }
}

val foo = implicitly[Foo]
assert(foo eq foo.next)

As with the magic case above this diverges due to the recursive implicit argument rec of method foo.
If we mark the implicit argument as by-name,

scala
trait Foo {
  def next: Foo
}

object Foo {
  implicit def foo(implicit rec: => Foo): Foo =
    new Foo { def next = rec }
}

val foo = implicitly[Foo]
assert(foo eq foo.next)

the example compiles with the assertion successful.

When compiled, recursive by-name implicit arguments of this sort are extracted out as val members of a local synthetic object at call sites as follows,

scala
val foo: Foo = scala.Predef.implicitly[Foo](
  {
    object LazyDefns$1 {
      val rec$1: Foo = Foo.foo(rec$1)
                       //      ^^^^^
                       // recursive knot tied here
    }
    LazyDefns$1.rec$1
  }
)
assert(foo eq foo.next)

Note that the recursive use of rec$1 occurs within the by-name argument of foo and is consequently deferred.
The desugaring matches what a programmer would do to construct such a recursive value explicitly.

To prevent infinite expansions, such as the magic example above, the compiler keeps track of a stack of “open implicit types” for which implicit arguments are currently being searched.
Whenever an implicit argument for type ´T´ is searched, ´T´ is added to the stack paired with the implicit definition which produces it, and whether it was required to satisfy a by-name implicit argument or not.
The type is removed from the stack once the search for the implicit argument either definitely fails or succeeds.
Everytime a type is about to be added to the stack, it is checked against existing entries which were produced by the same implicit definition and then,

  • if it is equivalent to some type which is already on the stack and there is a by-name argument between that entry and the top of the stack.
    In this case the search for that type succeeds immediately and the implicit argument is compiled as a recursive reference to the found argument.
    That argument is added as an entry in the synthesized implicit dictionary if it has not already been added.
  • otherwise if the core of the type dominates the core of a type already on the stack, then the implicit expansion is said to diverge and the search for that type fails immediately.
  • otherwise it is added to the stack paired with the implicit definition which produces it.
    Implicit resolution continues with the implicit arguments of that definition (if any).

Here, the core type of ´T´ is ´T´ with aliases expanded, top-level type annotations and refinements removed, and occurrences of top-level existentially bound variables replaced by their upper bounds.

A core type ´T´ dominates a type ´U´ if ´T´ is equivalent to ´U´, or if the top-level type constructors of ´T´ and ´U´ have a common element and ´T´ is more complex than ´U´ and the covering sets of ´T´ and ´U´ are equal.

The set of top-level type constructors ´\mathit{ttcs}(T)´ of a type ´T´ depends on the form of the type:

  • For a type designator, ´\mathit{ttcs}(p.c) = {c}´;
  • For a parameterized type, ´\mathit{ttcs}(p.c[\mathit{targs}]) = {c}´;
  • For a singleton type, ´\mathit{ttcs}(p.type) = \mathit{ttcs}(T)´, provided ´p´ has type ´T´;
  • For a compound type, ´\mathit{ttcs}(T_1´ with ... with ´T_n)´ ´= \mathit{ttcs}(T_1) \cup ... \cup \mathit{ttcs}(T_n)´.

The complexity ´\operatorname{complexity}(T)´ of a core type is an integer which also depends on the form of the type:

  • For a type designator, ´\operatorname{complexity}(p.c) = 1 + \operatorname{complexity}(p)´
  • For a parameterized type, ´\operatorname{complexity}(p.c[\mathit{targs}]) = 1 + \Sigma \operatorname{complexity}(\mathit{targs})´
  • For a singleton type denoting a package ´p´, ´\operatorname{complexity}(p.type) = 0´
  • For any other singleton type, ´\operatorname{complexity}(p.type) = 1 + \operatorname{complexity}(T)´, provided ´p´ has type ´T´;
  • For a compound type, ´\operatorname{complexity}(T_1´ with ... with ´T_n)´ ´= \Sigma\operatorname{complexity}(T_i)´

The covering set ´\mathit{cs}(T)´ of a type ´T´ is the set of type designators mentioned in a type.
For example, given the following,

scala
type A = List[(Int, Int)]
type B = List[(Int, (Int, Int))]
type C = List[(Int, String)]

the corresponding covering sets are:

  • ´\mathit{cs}(A)´: List, Tuple2, Int
  • ´\mathit{cs}(B)´: List, Tuple2, Int
  • ´\mathit{cs}(C)´: List, Tuple2, Int, String

Example

When typing sort(xs) for some list xs of type List[List[List[Int]]], the sequence of types for which implicit arguments are searched is

scala
List[List[Int]] => Ordered[List[List[Int]]],
List[Int] => Ordered[List[Int]],
Int => Ordered[Int]

All types share the common type constructor scala.Function1, but the complexity of each new type is lower than the complexity of the previous types.
Hence, the code typechecks.

Example

Let ys be a list of some type which cannot be converted to Ordered.
For instance:

scala
val ys = List(new IllegalArgumentException, new ClassCastException, new Error)

Assume that the definition of magic above is in scope.
Then the sequence of types for which implicit arguments are searched is

scala
Throwable => Ordered[Throwable],
Throwable => Ordered[Throwable],
...

Since the second type in the sequence is equal to the first, the compiler will issue an error signalling a divergent implicit expansion.

Views

Implicit 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 type ´S´ => ´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's expected type ´\mathit{pt}´.
    In this case an implicit ´v´ is searched which is applicable to ´e´ and whose result type conforms to ´\mathit{pt}´.
    The search proceeds as in the case of implicit parameters, where the implicit scope is the one of ´T´ => ´\mathit{pt}´.
    If such a view 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 an accessible member of ´T´.
    In this case, a view ´v´ is searched which is applicable to ´e´ and whose result contains a member named ´m´.
    The search proceeds as in the case 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´.
  3. In a selection ´e.m(\mathit{args})´ with ´e´ of type ´T´, if the selector ´m´ denotes some member(s) of ´T´, but none of these members is applicable to the arguments ´\mathit{args}´.
    In this case a view ´v´ is searched which is applicable to ´e´ and whose result contains a method ´m´ which is applicable to ´\mathit{args}´.
    The search proceeds as in the case of implicit parameters, where the implicit scope is the one of ´T´ => ´\mathit{pt}´, with ´\mathit{pt}´ being the structural type ´{ def m(\mathit{args}: T_1 , ... , T_n): U }´. If such a view is found, the selection ´e.m´ is converted to ´v´(´e´).´m(\mathit{args})´.

The implicit view, if it is found, can accept its argument ´e´ as a call-by-value or as a call-by-name parameter.
However, call-by-value implicits take precedence over call-by-name implicits.

As for implicit parameters, overloading resolution is applied if there are several possible candidates (of either the call-by-value or the call-by-name category).

Example Ordered

Class scala.Ordered[A] contains a method

scala
def <= [B >: A](that: B)(implicit b2ordered: B => Ordered[B]): Boolean

Assume two lists xs and ys of type List[Int] and assume that the list2ordered and int2ordered methods defined here are in scope.
Then the operation

scala
xs <= ys

is legal, and is expanded to:

scala
list2ordered(xs)(int2ordered).<=
    (ys)
    (xs => list2ordered(xs)(int2ordered))

The first application of list2ordered converts the list xs to an instance of class Ordered, whereas the second occurrence is part of an implicit parameter passed to the <= method.

Context Bounds and View Bounds

ebnf
TypeParam ::= (id | ‘_’) [TypeParamClause] [‘>:’ Type] [‘<:’ Type]
                {‘<%’ Type} {‘:’ Type}

A type parameter ´A´ of a method or non-trait class may have one or more view bounds ´A´ <% ´T´.
In this case the type parameter may be instantiated to any type ´S´ 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 context bounds ´A´ : ´T´.
In this case the type parameter may be instantiated to any type ´S´ 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 is treated 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:

scala
def ´f´[´A´ <% ´T_1´ ... <% ´T_m´ : ´U_1´ : ´U_n´](´\mathit{ps}´): ´R´ = ...

Then the method definition above is expanded to

scala
def ´f´[´A´](´\mathit{ps}´)(implicit ´v_1´: ´A´ => ´T_1´, ..., ´v_m´: ´A´ => ´T_m´,
                       ´w_1´: ´U_1´[´A´], ..., ´w_n´: ´U_n´[´A´]): ´R´ = ...

where the ´v_i´ 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, each such type parameter is expanded into evidence parameters in the order they appear and all the resulting evidence parameters are concatenated in one implicit parameter section.
Since traits do not take constructor parameters, this translation does not work for them.
Consequently, type-parameters in traits may not be view- or context-bounded.

Evidence parameters are prepended to the existing implicit parameter section, if one exists.

For example:

scala
def foo[A: M](implicit b: B): C
// expands to:
// def foo[A](implicit evidence´1: M[A], b: B): C

Example

The <= method from the Ordered example can be declared more concisely as follows:

scala
def <= [B >: A <% Ordered[B]](that: B): Boolean

Manifests

Manifests are type descriptors that can be automatically generated by the Scala compiler as arguments to implicit parameters.
The Scala standard library contains a hierarchy of four manifest classes, with OptManifest at the top.
Their signatures follow the outline below.

scala
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 class OptManifest[T], a manifest is determined for ´M[S]´, according to the following rules.

First if there is already an implicit argument that matches ´M[T]´, this argument is selected.

Otherwise, let ´\mathit{Mobj}´ be the companion object scala.reflect.Manifest if ´M´ is trait Manifest, 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 otherwise.
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 invocation ´\mathit{Mobj}´.arrayType[S](m), where ´m´ is the manifest determined for ´M[S]´.
  3. If ´T´ is some other class type ´S´#´C[U_1, ..., U_n]´ where the prefix type ´S´ cannot be statically determined from the class ´C´, a manifest is generated with the invocation ´\mathit{Mobj}´.classType[T](´m_0´, classOf[T], ´ms´) where ´m_0´ is the manifest determined for ´M'[S]´ and ´ms´ are the manifests determined for ´M'[U_1], ..., M'[U_n]´.
  4. If ´T´ is some other class type with type arguments ´U_1, ..., U_n´, a manifest is generated with the invocation ´\mathit{Mobj}´.classType[T](classOf[T], ´ms´) where ´ms´ are the manifests determined for ´M'[U_1], ..., M'[U_n]´.
  5. If ´T´ is a singleton type ´p´.type, a manifest is generated with the invocation ´\mathit{Mobj}´.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 ´T_1´ with ... with ´T_n´ where ´n > 1´, the result depends on whether a full manifest is to be determined or not.
    If ´M´ is trait Manifest, then a manifest is generated with the invocation Manifest.intersectionType[T](´ms´) where ´ms´ are the manifests determined for ´M[T_1], ..., M[T_n]´.
    Otherwise, if ´M´ is trait ClassManifest, then a manifest is generated for the intersection dominator of the types ´T_1, ..., T_n´.
  8. If ´T´ is some other type, then if ´M´ is trait OptManifest, a manifest is generated from the designator scala.reflect.NoManifest.
    If ´M´ is a type different from OptManifest, a static error results.

Spec 08 Pattern Matching (`docs/_spec/08-pattern-matching.md`)


title: Pattern Matching layout: default chapter: 8

Pattern Matching

Patterns

ebnf
Pattern         ::=  Pattern1 { ‘|’ Pattern1 }
  Pattern1        ::=  boundvarid ‘:’ TypePat
                    |  ‘_’ ‘:’ TypePat
                    |  Pattern2
  Pattern2        ::=  id [‘@’ Pattern3]
                    |  Pattern3
  Pattern3        ::=  SimplePattern
                    |  SimplePattern {id [nl] SimplePattern}
  SimplePattern   ::=  ‘_’
                    |  varid
                    |  Literal
                    |  StableId
                    |  StableId ‘(’ [Patterns] ‘)’
                    |  StableId ‘(’ [Patterns ‘,’] [id ‘@’] ‘_’ ‘*’ ‘)’
                    |  ‘(’ [Patterns] ‘)’
                    |  XmlPattern
  Patterns        ::=  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 defined by a pattern, and, if it does, binds the variables in the pattern to the corresponding components of the value (or sequence of values).
The same variable name may not be bound more than once in a pattern.

Example

Some examples of patterns are:

  1. The pattern ex: IOException matches all instances of class IOException, binding variable ex to the instance.
  2. The pattern Some(x) matches values of the form Some(´v´), binding x to the argument value ´v´ of the Some constructor.
  3. The pattern (x, _) matches pairs of values, binding x to the first component of the pair. The second component is matched with a wildcard pattern.
  4. The pattern x :: y :: xs matches lists of length ´\geq 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.

Variable Patterns

ebnf
SimplePattern   ::=  ‘_’
                    |  varid

A 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 the expected type of the pattern as given from outside.
A special case is the wild-card pattern _ which is treated as if it was a fresh variable on each occurrence.

Typed Patterns

ebnf
Pattern1        ::=  varid ‘:’ TypePat
                    |  ‘_’ ‘:’ TypePat

A 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 a fresh, unknown type.
This pattern matches any value matched by the type pattern ´T´; it binds the variable name to that value.

Pattern Binders

ebnf
Pattern2        ::=  varid ‘@’ Pattern3

A pattern binder ´x´@´p´ consists of a pattern variable ´x´ and a pattern ´p´.
The type of the variable ´x´ is the static type ´T´ implied by the pattern ´p´.
This pattern matches any value ´v´ matched by the pattern ´p´, and it binds the variable name to that value.

A pattern ´p´ implies a type ´T´ if the pattern matches only values of the type ´T´.

Literal Patterns

ebnf
SimplePattern   ::=  Literal

A 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.

Interpolated string patterns

ebnf
Literal  ::=  interpolatedString

The expansion of interpolated string literals in patterns is the same as in expressions.
If it occurs in a pattern, a interpolated string literal of either of the forms

text
id"text0{ pat1 }text1 ... { patn }textn"
id"""text0{ pat1 }text1 ... { patn }textn"""

is equivalent to:

text
StringContext("""text0""", ..., """textn""").id(pat1, ..., patn)

You could define your own StringContext to shadow the default one that's in the scala package.

This expansion is well-typed if the member id evaluates to an extractor object.
If the extractor object has apply as well as unapply or unapplySeq methods, processed strings can be used as either expressions or patterns.

Taking XML as an example

scala
implicit class XMLinterpolation(s: StringContext) = {
    object xml {
        def apply(exprs: Any*) =
            // parse ‘s’ and build an XML tree with ‘exprs’
            //in the holes
        def unapplySeq(xml: Node): Option[Seq[Node]] =
          // match `s’ against `xml’ tree and produce
          //subtrees in holes
    }
}

Then, XML pattern matching could be expressed like this:

scala
case xml"""
      <body>
        <a href = "some link"> $linktext </a>
      </body>
     """ => ...

where linktext is a variable bound by the pattern.

Stable Identifier Patterns

ebnf
SimplePattern   ::=  StableId

A stable identifier pattern is a stable identifier ´r´.
The type of ´r´ must conform to the expected type of the pattern.
The pattern matches any value ´v´ such that ´r´ == ´v´ (see here).

To resolve the syntactic overlap with a variable pattern, a stable identifier pattern may not be a simple name starting with a lower-case letter.
However, it is possible to enclose such a variable name in backquotes; then it is treated as a stable identifier pattern.

Example

Consider the following class definition:

scala
class C { c =>
  val x = 42
  val y = 27
  val Z = 8
  def f(x: Int) = x match {
    case c.x => 1  // matches 42
    case `y` => 2  // matches 27
    case Z   => 3  // matches 8
    case x   => 4  // matches any value
  }
}

Here, the first three patterns are stable identifier patterns, while the last one is a variable pattern.

Constructor Patterns

ebnf
SimplePattern   ::=  StableId ‘(’ [Patterns] ‘)’

A constructor pattern is of the form ´c(p_1, ..., p_n)´ where ´n \geq 0´. It consists of a stable identifier ´c´, followed by element patterns ´p_1, ..., p_n´.
The constructor ´c´ is a simple or qualified name which denotes a case class.
If the case class is monomorphic, then it must conform to the expected type of the pattern, and the formal parameter types of ´x´'s primary constructor are taken as the expected types of the element patterns ´p_1, ..., p_n´.
If the case class is polymorphic, then its type parameters are instantiated so that the instantiation of ´c´ conforms to the expected type of the pattern.
The instantiated formal parameter types of ´c´'s primary constructor are then taken as the expected types of the component patterns ´p_1, ..., p_n´.
The pattern matches all objects created from constructor invocations ´c(v_1, ..., v_n)´ where each element pattern ´p_i´ matches the corresponding value ´v_i´.

A special case arises when ´c´'s formal parameter types end in a repeated parameter.
This is further discussed here.

Record Patterns

ebnf
SimplePattern   ::=  StableId ‘(’ [Patterns] ‘)’

A record pattern ´r(p_1, ..., p_n)´ where ´n \geq 0´ is of the same syntactic form as a constructor pattern.
However, instead of a case class, the stable identifier ´r´ denotes a class defined in Java as a record, with ´n´ components of types ´T_1, ..., T_n´.
A record pattern applies only if ´r´ does not define an unapply or unapplySeq method; otherwise the pattern is an extractor pattern.

If the record class is monomorphic, then it must conform to the expected type of the pattern, and the component types ´T_1, ..., T_n´ are taken as the expected types of the element patterns ´p_1, ..., p_n´.
If the record class is polymorphic, then its type parameters are instantiated so that the instantiation of ´r´ conforms to the expected type of the pattern.
The instantiated component types are then taken as the expected types of the element patterns ´p_1, ..., p_n´.
The pattern matches all instances ´v´ of the record class where each element pattern ´p_i´ matches the corresponding component of ´v´.

A special case arises when ´r´'s last component is a repeated parameter (a Java vararg).
This is further discussed here.

Example

Given the Java records

java
public record Rec1(int x, String y) {}
public record Rec2<T>(int x, T y) {}

both patterns below are record patterns:

scala
(r1: Rec1) match {
  case Rec1(i, s) => ...   // i: Int, s: String
}
(r2: Rec2[String]) match {
  case Rec2(i, s) => ...   // i: Int, s: String
}

The pattern Rec1(i, s) matches any Rec1, binding i and s to its two components.
For the polymorphic Rec2, the type parameter T is instantiated to String so that the pattern conforms to the expected type Rec2[String]; hence s is typed as String.

Example

If a record additionally declares an extractor, the extractor takes precedence:

java
public record RecUnapply(int i, String s) {
  public static scala.Tuple2<Integer, String> unapply(RecUnapply r) { return new scala.Tuple2<>(1, "other"); }
}

Here RecUnapply(i, s) is an extractor pattern using the declared unapply method, rather than a record pattern.

Tuple Patterns

ebnf
SimplePattern   ::=  ‘(’ [Patterns] ‘)’

A tuple pattern (´p_1´, ..., ´p_n´) where ´n \geq 2´ is equivalent to ´p_1´ *: ... *: ´p_n´ *: scala.EmptyTuple.

Notes:

  • () is equivalent to _: scala.Unit, and not scala.EmptyTuple.
  • (´pat´) is a pattern matching ´pat´, and not ´pat´ *: scala.EmptyTuple.
  • As such patterns with *: are slow, a more efficient translation is free to be implemented. For example, (´p_1´, ´p_2´) could be translated to scala.Tuple2(´p_1´, ´p_2´), which is indeed equivalent to ´p_1´ *: ´p_2´ *: scala.EmptyTuple.

Extractor Patterns

ebnf
SimplePattern   ::=  StableId ‘(’ [Patterns] ‘)’

An extractor pattern ´x(p_1, ..., p_n)´ where ´n \geq 0´ is of the same syntactic form as a constructor pattern.
However, instead of a case class, the stable identifier ´x´ denotes an object which has a member method named unapply or unapplySeq that matches the pattern.

An extractor pattern cannot match the value null. The implementation ensures that the unapply/unapplySeq method is not applied to null.

A type is said to be an extractor type for some type T if it has a method get with return type T, and a method isEmpty with a return type that conforms to Boolean.
Option[T] is an extractor type for type T.

An unapply method in an object ´x´ matches the pattern ´x(p_1, ..., p_n)´ if it has a single parameter (and, optionally, an implicit parameter list) and one of the following applies:

  • ´n=0´ and unapply's result type conforms to Boolean.
    In this case the extractor pattern matches all values ´v´ for which ´x´.unapply(´v´) yields true.
  • ´n=1´ and unapply's result type is an extractor type for some type ´T´.
    In this case, the (only) argument pattern ´p_1´ is typed in turn with expected type ´T´.
    The extractor pattern matches then all values ´v´ for which ´x´.unapply(´v´) yields a value ´u´ for which ´u´.isEmpty yields false, ´u´.get yields a value ´v_1´, and ´p_1´ matches ´v_1´.
  • ´n>1´ and unapply's result type is an extractor type for some type ´T´ with members ´_1, ..., _n´ returning types ´T_1, ..., T_n´.
    In this case, the argument patterns ´p_1, ..., p_n´ are typed in turn with expected types ´T_1 , ..., T_n´.
    The extractor pattern matches then all values ´v´ for which ´x´.unapply(´v´) yields a value ´u´ for which ´u´.isEmpty yields false, ´u´.get yields some value ´t´, and each pattern ´p_i´ matches the corresponding value ´t._1´ from ´t._1, ..., t._n´.

An unapplySeq method in an object ´x´ matches the pattern ´x(q_1, ..., q_m, p_1, ..., p_n)´ if it takes exactly one argument and its result type is of the form Option[(´T_1, ..., T_m´, Seq[S])] (if m = 0, the type Option[Seq[S]] is also accepted).
This case is further discussed below.

Example 1

If we define an extractor object Pair:

scala
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 formation as well as for deconstruction of tuples in patterns.
Hence, the following is possible:

scala
val x = (1, 2)
val y = x match {
  case Pair(i, s) => Pair(s + i, i * i)
}

Example 2

If we define a class NameBased

scala
class NameBased[A, B](a: A, b: B) {
  def isEmpty = false
  def get = this
  def _1 = a
  def _2 = b
}

Then NameBased is an extractor type for NameBased itself, since it has a member isEmpty returning a value of type Boolean, and it has a member get returning a value of type NameBased.

Since it also has members _1 and _2, it can be used in an extractor pattern with n = 2 as follows:

scala
object Extractor {
  def unapply(x: Any) = new NameBased(1, "two")
}

"anything" match {
  case Extractor(a, b) => println(s"\$a, \$b") //prints "1, two"
}

Pattern Sequences

ebnf
SimplePattern ::= StableId ‘(’ [Patterns ‘,’] [varid ‘@’] ‘_’ ‘*’ ‘)’

A pattern sequence ´p_1, ..., p_n´ appears in three contexts.
First, in a constructor pattern ´c(q_1, ..., q_m, p_1, ..., p_n)´, where ´c´ is a case class which has ´m+1´ primary constructor parameters, ending in a repeated parameter of type S*.
Second, in an extractor pattern ´x(q_1, ..., q_m, p_1, ..., p_n)´ if the extractor object ´x´ does not have an unapply method, but it does define an unapplySeq method with a result type that is an extractor type for type (T_1, ... , T_m, Seq[S]) (if m = 0, an extractor type for the type Seq[S] is also accepted). The expected type for the patterns ´p_i´ is ´S´.
Third, in a record pattern ´r(q_1, ..., q_m, p_1, ..., p_n)´, where ´r´ is a Java record which has ´m+1´ components, ending in a repeated parameter of type S* (a Java vararg).

The last pattern in a pattern sequence may be a sequence wildcard _*.
Each element pattern ´p_i´ is type-checked with ´S´ as expected type, unless it is a sequence wildcard.
If a final sequence wildcard is present, the pattern matches all values ´v´ that are sequences which start with elements matching patterns ´p_1, ..., p_{n-1}´.
If no final sequence wildcard is given, the pattern matches all values ´v´ that are sequences of length ´n´ which consist of elements matching patterns ´p_1, ..., p_n´.

Infix Operation Patterns

ebnf
Pattern3  ::=  SimplePattern {id [nl] SimplePattern}

An infix operation pattern ´p;\mathit{op};q´ is a shorthand for the
constructor or extractor pattern ´\mathit{op}(p, q)´.
The precedence and associativity of operators in patterns is the same as in expressions.

An infix operation pattern ´p;\mathit{op};(q_1, ..., q_n)´ is a shorthand for the constructor or extractor pattern ´\mathit{op}(p, q_1, ..., q_n)´.

Pattern Alternatives

ebnf
Pattern   ::=  Pattern1 { ‘|’ Pattern1 }

A pattern alternative ´p_1´ | ... | ´p_n´ consists of a number of alternative patterns ´p_i´.
All alternative patterns are type checked with the expected type of the pattern.
They may not bind variables other than wildcards.
The alternative pattern matches a value ´v´ if at least one its alternatives matches ´v´.

XML Patterns

XML patterns are treated here.

Regular Expression Patterns

Regular expression patterns have been discontinued in Scala from version 2.0.

Later version of Scala provide a much simplified version of regular expression patterns that cover most scenarios of non-text sequence processing.
A sequence pattern is a pattern that stands in a position where either (1) a pattern of a type T which is conforming 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 position stands for arbitrary long sequences.
It can be bound to variables using @, as usual, in which case the variable will have the type Seq[A].

Irrefutable Patterns

A 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(p_1, ..., p_n)´, the type ´T´ is an instance of class ´c´, the primary constructor of type ´T´ has argument types ´T_1, ..., T_n´, and each ´p_i´ is irrefutable for ´T_i´.
  4. ´p´ is a record pattern ´r(p_1, ..., p_n)´, the type ´T´ is an instance of the record class ´r´ with component types ´T_1, ..., T_n´, and each ´p_i´ is irrefutable for ´T_i´.
  5. ´p´ is an extractor pattern for which the extractor type is Some[´T´] for some type ´T´
  6. ´p´ is an extractor pattern for which the extractor types isEmpty method is the singleton type false
  7. ´p´ is an extractor pattern for which the return type is the singleton type true

Type Patterns

ebnf
TypePat           ::=  Type

Type patterns consist of types, type variables, and wildcards.
A type pattern ´T´ is of one 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 exists, is relevant for determining class instances.
    For instance, the pattern ´p.C´ matches only instances of classes ´C´ which were created with the path ´p´ as prefix.
    This also applies to prefixes which are not given syntactically.
    For example, if ´C´ refers to a class defined in the nearest enclosing class and is thus equivalent to ´this.C´, it is considered to have a prefix.

The bottom types scala.Nothing and scala.Null cannot be used as type patterns, 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´ (the eq method is used to compare the matched value to ´p´).

  • A literal type ´lit´. This type pattern matches only the value denoted by the literal ´lit´ (the == method is used to compare the matched value to ´lit´).

  • A compound type pattern ´T_1´ with ... with ´T_n´ where each ´T_i´ is a type pattern.
    This type pattern matches all values that are matched by each of the type patterns ´T_i´.

  • A parameterized type pattern ´T[a_1, ..., a_n]´, where the ´a_i´ are type variable patterns or wildcards _.
    This type pattern matches all values which match ´T´ for some arbitrary instantiation of the type variables and wildcards.
    The bounds or alias type of these type variable are determined as described here.

  • A parameterized type pattern scala.Array´[T_1]´, where ´T_1´ is a type pattern.
    This type pattern matches any non-null instance of type scala.Array´[U_1]´, where ´U_1´ is a type matched by ´T_1´.

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.
The Scala compiler will issue an "unchecked" warning for these patterns to flag the possible loss of type-safety.

A type variable pattern is a simple identifier which starts with a lower case letter.

Type Parameter Inference in Patterns

Type parameter inference is the process of finding bounds for the bound type variables in a typed pattern or constructor pattern.
Inference takes into account the expected type of the pattern.

Type parameter inference for typed patterns

Assume a typed pattern ´p: T'´. Let ´T´ result from ´T'´ where all wildcards in ´T'´ are renamed to fresh variable names.
Let ´a_1, ..., a_n´ be the type variables in ´T´.
These type variables are considered bound in the pattern.
Let the expected type of the pattern be ´\mathit{pt}´.

Type parameter inference constructs first a set of subtype constraints over the type variables ´a_i´.
The initial constraints set ´\mathcal{C}_0´ reflects just the bounds of these type variables.
That is, assuming ´T´ has bound type variables ´a_1, ..., a_n´ which correspond to class type parameters ´a_1', ..., a_n'´ with lower bounds ´L_1, ..., L_n´ and upper bounds ´U_1, ..., U_n´, ´\mathcal{C}_0´ contains the constraints

$$
\begin{cases}
a_i &<: \sigma U_i & \quad (i = 1, ..., n) \\
\sigma L_i &<: a_i & \quad (i = 1, ..., n)
\end{cases}
$$

where ´\sigma´ is the substitution ´[a_1' := a_1, ..., a_n' :=a_n]´.

The set ´\mathcal{C}_0´ is then augmented by further subtype constraints.
There are two cases.

Case 1

If there exists a substitution ´\sigma´ over the type variables ´a_i, ..., a_n´ such that ´\sigma T´ conforms to ´\mathit{pt}´, one determines the weakest subtype constraints ´\mathcal{C}_1´ over the type variables ´a_1, ..., a_n´ such that ´\mathcal{C}_0 \wedge \mathcal{C}_1´ implies that ´T´ conforms to ´\mathit{pt}´.

Case 2

Otherwise, if ´T´ can not be made to conform to ´\mathit{pt}´ by instantiating its type variables, one determines all type variables in ´\mathit{pt}´ which are defined as type parameters of a method enclosing the pattern.
Let the set of such type parameters be ´b_1 , ..., b_m´.
Let ´\mathcal{C}_0'´ be the subtype constraints reflecting the bounds of the type variables ´b_i´.
If ´T´ denotes an instance type of a final class, let ´\mathcal{C}_2´ be the weakest set of subtype constraints over the type variables ´a_1, ..., a_n´ and ´b_1, ..., b_m´ such that ´\mathcal{C}_0 \wedge \mathcal{C}_0' \wedge \mathcal{C}_2´ implies that ´T´ conforms to ´\mathit{pt}´.
If ´T´ does not denote an instance type of a final class, let ´\mathcal{C}_2´ be the weakest set of subtype constraints over the type variables ´a_1, ..., a_n´ and ´b_1, ..., b_m´ such that ´\mathcal{C}_0 \wedge \mathcal{C}_0' \wedge \mathcal{C}_2´ implies that it is possible to construct a type ´T'´ which conforms to both ´T´ and ´\mathit{pt}´.
It is a static error if there is no satisfiable set of constraints ´\mathcal{C}_2´ 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 ´a_i >: L_i <: U_i´ where each ´L_i´ is minimal and each ´U_i´ is maximal wrt ´<:´ such that ´a_i >: L_i <: U_i´ for ´i = 1, ..., n´ implies ´\mathcal{C}_0 \wedge \mathcal{C}_1´.

Case 2

We take ´a_i >: L_i <: U_i´ and ´b_i >: L_i' <: U_i' ´ where each ´L_i´ and ´L_j'´ is minimal and each ´U_i´ and ´U_j'´ is maximal such that ´a_i >: L_i <: U_i´ for ´i = 1, ..., n´ and ´b_j >: L_j' <: U_j'´ for ´j = 1, ..., m´ implies ´\mathcal{C}_0 \wedge \mathcal{C}_0' \wedge \mathcal{C}_2´.

In both cases, local type inference is permitted to limit the complexity of inferred bounds.
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 pattern ´C(p_1, ..., p_n)´ where class ´C´ has type parameters ´a_1, ..., a_n´.
These type parameters are inferred in the same way as for the typed pattern (_: ´C[a_1, ..., a_n]´).

Example

Consider the program fragment:

scala
val x: Any
x match {
  case y: List[a] => ...
}

Here, the type pattern List[a] is matched against the expected type Any.
The pattern binds the type variable a.
Since List[a] conforms to Any for every type argument, 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 as

scala
val 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 upper bound List[String].

Example

Consider the program fragment:

scala
val x: Any
x match {
  case y: List[String] => ...
}

Scala does not maintain information about type arguments at run-time, so there is no way to check that x is a list of strings.
Instead, the Scala compiler will erase the pattern to List[_]; that is, it will only test whether the top-level runtime-class of the value x conforms to List, and the pattern match will succeed if it does.
This might 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

Consider the program fragment

scala
class Term[A]
class 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 not conform 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.
In our 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 to conform to the method's declared result type, Number.

Pattern Matching Expressions

ebnf
InfixExpr       ::=  InfixExpr MatchClause
  SimpleExpr      ::=  SimpleExpr ‘.’ MatchClause
  Expr            ::=  PostfixExpr ‘match’ ‘{’ CaseClauses ‘}’
  CaseClauses     ::=  CaseClause {CaseClause}
  CaseClause      ::=  ‘case’ Pattern [Guard] ‘=>’ Block
  ExprCaseClause  ::=  ‘case’ Pattern [Guard] ‘=>’ Expr

A pattern matching expression

scala
e match { case ´p_1´ => ´b_1´ ... case ´p_n´ => ´b_n´ }

consists of a selector expression ´e´ and a number ´n > 0´ of cases.
Each case consists of a (possibly guarded) pattern ´p_i´ and a block ´b_i´.
Each ´p_i´ might be complemented by a guard if ´e´ where ´e´ is a boolean expression.
The scope of the pattern variables in ´p_i´ comprises the pattern's guard and the corresponding block ´b_i´.

Let ´T´ be the type of the selector expression ´e´ and let ´a_1, ..., a_m´ be the type parameters of all methods enclosing the pattern matching expression.
For every ´a_i´, let ´L_i´ be its lower bound and ´U_i´ be its higher bound.
Every pattern ´p \in {p_1,, ..., p_n}´ can be 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 ´T´ by replacing every occurrence of a type parameter ´a_i´ by
undefined.
If this second step fails also, a compile-time error results.
If the second step succeeds, let ´T_p´ be the type of pattern ´p´ seen as an expression.
One then determines minimal bounds ´L_11, ..., L_m'´ and maximal bounds ´U_1', ..., U_m'´ such that for all ´i´, ´L_i <: L_i'´ and ´U_i' <: U_i´ and the following constraint system is satisfied:

$$
L_1 <: a_1 <: U_1;\wedge;...;\wedge;L_m <: a_m <: U_m \ \Rightarrow\ T_p <: T
$$

If 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 assumption that each ´a_i´ has lower bound ´L_i'´ instead of ´L_i´ and has upper bound ´U_i'´ instead of ´U_i´.

The expected type of every block ´b_i´ is the expected type of the whole pattern matching expression.
If there is no expected type, harmonization is attempted on the list of all blocks ´b_i´.
The type of the pattern matching expression is then the least upper bound of the types of all blocks ´b_i´ after harmonization.

When applying a pattern matching expression to a selector value, patterns are tried in sequence until one is found which matches the selector value.
Say this case is case ´p_i \Rightarrow b_i´.
The result of the whole expression is the result of evaluating ´b_i´, where all pattern variables of ´p_i´ 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 boolean expression ´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 as normal.
If the guard expression evaluates to false, the pattern in the case is considered not to match and the search for a matching pattern continues.

In the interest of efficiency the evaluation of a pattern matching expression may try patterns in some other order than textual sequence.
This might affect evaluation through 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, a union type, a Java record, or a combination thereof, the compilation 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 raised at run-time.

Example

Consider the following definitions of arithmetic terms:

scala
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 a conditional.
Every term carries as a type parameter the type of the expression it represents (either Int or Boolean).

A type-safe evaluator for such terms can be written as follows.

scala
def eval[T](t: Term[T]): T = t match {
  case Lit(n)        => n
  case Succ(u)       => eval(u) + 1
  case IsZero(u)     => eval(u) == 0
  case If(c, u1, u2) => eval(if (eval(c)) u1 else u2)
}

Note that the evaluator makes crucial use of the fact that type parameters of enclosing methods can acquire new bounds through pattern matching.

For instance, the type of the pattern in the second case, Succ(u), is Int.
It conforms to 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.

Pattern Matching Anonymous Functions

ebnf
BlockExpr ::= ‘{’ CaseClauses ‘}’

An anonymous function can be defined by a sequence of cases

scala
{ case ´p_1´ => ´b_1´ ... case ´p_n´ => ´b_n´ }

which appear as an expression without a prior match.
The expected type of such an expression must in part be defined.
It must be either scala.Function´k´[´S_1, ..., S_k´, ´R´] for some ´k > 0´, or scala.PartialFunction[´S_1´, ´R´], where the argument type(s) ´S_1, ..., S_k´ must be fully determined, but the result type ´R´ may be undetermined.

If the expected type is SAM-convertible to scala.Function´k´[´S_1, ..., S_k´, ´R´], the expression is taken to be equivalent to the anonymous function:

scala
(´x_1: S_1, ..., x_k: S_k´) => (´x_1, ..., x_k´) match {
  case ´p_1´ => ´b_1´ ... case ´p_n´ => ´b_n´
}

Here, each ´x_i´ is a fresh name.
As was shown here, this anonymous function is in turn equivalent to the following instance creation expression, where ´T´ is the least upper bound of the types of all ´b_i´.

scala
new scala.Function´k´[´S_1, ..., S_k´, ´T´] {
  def apply(´x_1: S_1, ..., x_k: S_k´): ´T´ = (´x_1, ..., x_k´) match {
    case ´p_1´ => ´b_1´ ... case ´p_n´ => ´b_n´
  }
}

If the expected type is scala.PartialFunction[´S´, ´R´], the expression is taken to be equivalent to the following instance creation expression:

scala
new scala.PartialFunction[´S´, ´T´] {
  def apply(´x´: ´S´): ´T´ = x match {
    case ´p_1´ => ´b_1´ ... case ´p_n´ => ´b_n´
  }
  def isDefinedAt(´x´: ´S´): Boolean = x match {
    case ´p_1´ => true ... case ´p_n´ => true
    case _ => false
  }
}

Here, ´x´ is a fresh name and ´T´ is the least upper bound of the types of all ´b_i´.
The final default case in the isDefinedAt method is omitted if one of the patterns ´p_1, ..., p_n´ is already a variable or wildcard pattern.

As a convenience, the partial function may be written using function literal notation:

scala
(´x: S´) => e(´x´) match {
  case ´p_1´ => ´b_1´ ... case ´p_n´ => ´b_n´
}

where the selector expression is used for matches in the expansion.
The body of the function must consist solely of the match expression.

This syntax permits annotating the selector:

scala
(´x: S´) => (e(´x´): @unchecked) match { ... }

Example

Here's an example which uses foldLeft to compute the scalar product of two vectors:

scala
def scalarProduct(xs: Array[Double], ys: Array[Double]) =
  (xs zip ys).foldLeft(0.0) {
    case (a, (b, c)) => a + b * c
  }

The case clauses in this code are equivalent to the following anonymous function:

scala
(x, y) => (x, y) match {
  case (a, (b, c)) => a + b * c
}

Spec 09 Top Level Definitions (`docs/_spec/09-top-level-definitions.md`)


title: Top-Level Definitions layout: default chapter: 9

Top-Level Definitions

Compilation Units

ebnf
CompilationUnit  ::=  {‘package’ QualId semi} TopStatSeq
TopStatSeq       ::=  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 class and object definitions, which may be preceded by a package clause.

A compilation unit

scala
package ´p_1´;
...
package ´p_n´;
´\mathit{stats}´

starting with one or more package clauses is equivalent to a compilation unit consisting of the packaging

scala
package ´p_1´ { ...
  package ´p_n´ {
    ´\mathit{stats}´
  } ...
}

Every compilation unit implicitly imports the following packages, in the given order:

  1. the package java.lang,
  2. the package scala, and
  3. the object scala.Predef, unless there is an explicit top-level import that references scala.Predef.

Members of a later import in that order hide members of an earlier import.

The exception to the implicit import of scala.Predef can be useful to hide, e.g., predefined implicit conversions.

Packagings

ebnf
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.
Instead, the set of members of a package is determined by packagings.

A packaging package ´p´ { ´\mathit{ds}´ } injects all definitions in ´\mathit{ds}´ as members into the package whose qualified name is ´p´.
Members of a package are called top-level definitions.
If a definition in ´\mathit{ds}´ is labeled private, it is visible only for other members in the package.

Inside the packaging, all members of package ´p´ are visible under their simple names.
However this rule does not extend to members of enclosing packages of ´p´ that are designated by a prefix of the path ´p´.

scala
package org.net.prj {
  ...
}

all members of package org.net.prj are visible under their simple names, but members 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, unlike other objects, packages may not be used as values.
It is illegal to have a package with the same fully qualified name as a module or a class.

Top-level definitions outside a packaging are assumed to be injected into a special empty package.
That package cannot be named and therefore cannot be imported.
However, members of the empty package are visible to each other without qualification.

Package Objects

ebnf
PackageObject   ::=  ‘package’ ‘object’ ObjectDef

A package object package object ´p´ extends ´t´ adds the members of template ´t´ to 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.scala that'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, the behavior of the program is currently undefined.
It is expected that this restriction will be lifted in a future version of Scala.

Package References

ebnf
QualId           ::=  id {‘.’ id}

A reference to a package takes the form of a qualified identifier.
Like all other references, 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 member named ´p´.

If a package name is shadowed, it's possible to refer to its fully-qualified name by prefixing it with the special predefined name _root_, which refers to the outermost root package that contains all top-level packages.

The name _root_ has this special denotation only when used as the first element of a qualifier; it is an ordinary identifier otherwise.

Example

Consider the following program:

scala
package b {
  class B
}

package a {
  package b {
    class A {
      val x = new _root_.b.B
    }
    class C {
      import _root_.b._
      def y = new 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 package a.b, and, provided that package does not also contain a class B, a compiler-time error would result.

Programs

A 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 program's command arguments are passed to the main method as a parameter of type 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 special class scala.App whose body acts as a main method.
An objects ´m´ inheriting from this class is thus a program, which executes the initialization code of the object ´m´.

Example

The following example will create a hello world program by defining a method main in module test.HelloWorld.

scala
package test
object HelloWorld {
  def main(args: Array[String]) { println("Hello World") }
}

This program can be started by the command

scala
scala test.HelloWorld

In a Java environment, the command

scala
java test.HelloWorld

would work as well.

HelloWorld can also be defined without a main method by inheriting from App instead:

scala
package test
object HelloWorld extends App {
  println("Hello World")
}

Spec 10 Xml Expressions And Patterns (`docs/_spec/10-xml-expressions-and-patterns.md`)


title: XML layout: default chapter: 10

XML Expressions and Patterns

By Burak Emir

This chapter describes the syntactic structure of XML expressions and patterns.
It follows as closely as possible the XML 1.0 specification, changes being mandated by the possibility of embedding Scala code fragments.

XML expressions

XML expressions are expressions generated by the following production, where the opening bracket < of the first element must be in a position to start the lexical XML mode.

ebnf
XmlExpr ::= XmlContent {Element}

Well-formedness constraints of the XML specification apply, which means for instance that start tags and end tags must match, and attributes may only be defined once, except for constraints related to entity resolution.

The following productions describe Scala's extensible markup language, designed as close as possible to the W3C extensible markup language standard.
Only the productions for attribute values and character data are changed.
Scala does not support declarations.
Entity references are not resolved at runtime.

ebnf
Element       ::=    EmptyElemTag
                |    STag Content ETag

EmptyElemTag  ::=    ‘<’ Name {S Attribute} [S] ‘/>’

STag          ::=    ‘<’ Name {S Attribute} [S] ‘>’
ETag          ::=    ‘</’ Name [S] ‘>’
Content       ::=    [CharData] {Content1 [CharData]}
Content1      ::=    XmlContent
                |    Reference
                |    ScalaExpr
XmlContent    ::=    Element
                |    CDSect
                |    PI
                |    Comment

If 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 expression consists of more than one element, then its value is a runtime representation of a sequence 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 instruction, or a comment, it is represented by an instance of the corresponding Scala runtime class.

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 compiler option.

ebnf
Attribute  ::=    Name Eq AttValue

AttValue      ::=    ‘"’ {CharQ | CharRef} ‘"’
                |    ‘'’ {CharA | CharRef} ‘'’
                |    ScalaExpr

ScalaExpr     ::=    Block

CharData      ::=   { CharNoRef } ´\textit{ without}´ {CharNoRef}‘{’CharB {CharNoRef}
                                  ´\textit{ 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 by a closing brace }.
To express a single opening braces within XML text as generated by CharData, it must be doubled.
Thus, {{ represents the XML text { and does not introduce an embedded Scala expression.

ebnf
BaseChar, CDSect, Char, Comment, CombiningChar, Ideographic, NameChar, PI, S, Reference
              ::=  ´\textit{“as in W3C XML”}´

Char1         ::=  Char ´\textit{ without}´ ‘<’ | ‘&’
CharQ         ::=  Char1 ´\textit{ without}´ ‘"’
CharA         ::=  Char1 ´\textit{ without}´ ‘'’
CharB         ::=  Char1 ´\textit{ without}´ ‘{’

Name          ::=  XNameStart {NameChar}

XNameStart    ::= ‘_’ | BaseChar | Ideographic
                 ´\textit{ (as in W3C XML, but without }´ ‘:’´)´

XML patterns

XML patterns are patterns generated by the following production, where the opening bracket < of the element patterns must be in a position to start the lexical XML mode.

ebnf
XmlPattern  ::= ElementPattern

Well-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 the pattern.
XML patterns may contain Scala patterns.

Whitespace is treated the same way as in XML expressions.

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 compiler option.

ebnf
ElemPattern   ::=    EmptyElemTagP
                |    STagP ContentP ETagP

EmptyElemTagP ::=    ‘<’  Name [S] ‘/>’
STagP         ::=    ‘<’  Name [S] ‘>’
ETagP         ::=    ‘</’ Name [S] ‘>’
ContentP      ::=    [CharData] {(ElemPattern|ScalaPatterns) [CharData]}
ContentP1     ::=    ElemPattern
                |    Reference
                |    CDSect
                |    PI
                |    Comment
                |    ScalaPatterns
ScalaPatterns ::=    ‘{’ Patterns ‘}’

Spec 11 Annotations (`docs/_spec/11-annotations.md`)


title: Annotations layout: default chapter: 11

Annotations

ebnf
Annotation       ::=  ‘@’ SimpleType {ArgumentExprs}
  ConstrAnnotation ::=  ‘@’ SimpleType ArgumentExprs

Definition

Annotations associate meta-information with definitions.
A simple annotation has the form @´c´ or @´c(a_1, ..., a_n)´.
Here, ´c´ is a constructor of a class ´C´, which must conform to the class scala.Annotation.

Annotations may apply to definitions, types, or expressions.
An annotation of a definition appears in front of that definition.
An annotation of a type appears after that type.
An annotation of an expression appears after that expression, 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:

scala
@deprecated("Use D", "1.0") class C { ... } // Class annotation
@transient @volatile var m: Int             // Variable annotation
String @local                               // Type annotation
(e: @unchecked) match { ... }               // Expression annotation

Predefined Annotations

Predefined annotations are found in the scala.annotation package, and also in the scala package.

Scala Compiler Annotations

  • @tailrec Marks a method which must be transformed by the compiler to eliminate self-recursive invocations in tail position.
    It is an error if there are no such invocations, or a recursive call not in tail position.

  • @switch Marks the expression submitted to a match as "switchable", such that the match can be compiled to an efficient form.
    The compiler will warn if the type of the expression is not a switchable type.
    Certain degenerate matches may remain unoptimized without a warning.

  • @unchecked When applied to the selector of a match expression, this attribute suppresses any warnings about non-exhaustive pattern matches that would otherwise be emitted.
    For instance, no warnings would be produced for the method definition below, or the similar value definition.

scala
def f(x: Option[Int]) = (x: @unchecked) match {
  case Some(y) => y
}
val Some(y) = x: @unchecked

Without the @unchecked annotation, a Scala compiler could infer that the pattern match is non-exhaustive and issue a warning because Option is a sealed class.

  • @uncheckedStable When applied to a value 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:
scala
type A { type T }
type B
@uncheckedStable val x: A with B // volatile type
val y: x.T                       // OK since `x' is still a path

Without the @uncheckedStable annotation, the designator x would not be a path since its type A with B is volatile.
Hence, the reference x.T would be malformed.

When applied to value definitions that have no volatile types, the annotation has no effect.

  • @specialized When applied to the definition of a type parameter, this annotation causes the compiler to generate definitions that are specialized for primitive types.
    An optional list of primitive types may be given, in which case specialization takes into account only those types.
    For instance, the following code would generate specialized traits for Unit, Int and Double
scala
trait Function0[@specialized(Unit, Int, Double) T] {
  def apply: T
}

Whenever the static type of an expression matches a specialized variant of a definition, the compiler will use the specialized version instead.
See the specialization sid for more details of the implementation.

Deprecation Annotations

  • @deprecated(message: <stringlit>, since: <stringlit>)
    Marks a definition as deprecated.
    Accesses to the defined entity cause the compiler to issue a deprecation warning with the message <stringlit>.
    The argument since documents since when the definition should be considered deprecated.
    Deprecated warnings are suppressed in code that belongs to a deprecated definition.

  • @deprecatedName(name: <stringlit>, since: <stringlit>)
    Marks a formal parameter name as deprecated.
    Invocations of this entity using named parameter syntax referring to the deprecated parameter name cause a deprecation warning.

Java Platform Annotations

The meaning of annotation clauses is implementation-dependent.
On the Java platform, the following annotations have a standard meaning.

  • @transient Marks a field to be non-persistent; this is equivalent to the transient modifier in Java.

  • @volatile Marks a field which can change its value outside the control of the program; this is equivalent to the volatile modifier in Java.

  • @SerialVersionUID(<longlit>) Attaches a serial version identifier (a long constant) to a class.
    This is equivalent to the following field definition in Java:

java
private final static SerialVersionUID = <longlit>
  • @throws(<classlit>) A Java compiler checks that a program contains handlers for checked exceptions by analyzing which checked exceptions can result from the execution of a method or constructor.
    For each checked exception which is a possible result, the throws clause for the method or constructor must mention the class of that exception or one of the superclasses of the class of that exception.

Java Beans Annotations

  • @scala.beans.BeanProperty When prefixed to a definition of some variable X, this annotation causes getter 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 appears capitalized after the get or set.
    When the annotation is added to the definition of an immutable value definition X, only a getter is generated.
    The construction of these methods is part of code-generation; therefore, these methods become visible only once a classfile for the containing class is generated.

  • @scala.beans.BooleanBeanProperty This annotation is equivalent to scala.reflect.BeanProperty, but the generated getter method is named isX instead of getX.

User-defined Annotations

Other annotations may be interpreted by platform- or application-dependent tools.
The class scala.annotation.Annotation is the base class for user-defined annotations. It has two sub-traits:

  • scala.annotation.StaticAnnotation: Instances of a subclass of this trait will be stored in the generated class files, and therefore accessible to runtime reflection and later compilation runs.
  • scala.annotation.ConstantAnnotation: Instances of a subclass of this trait may only have arguments which are constant expressions, and are also stored in the generated class files.
  • If an annotation class inherits from neither scala.ConstantAnnotation nor scala.StaticAnnotation, its instances are visible only locally during the compilation run that analyzes them.

Host-platform Annotations

The host platform may define its own annotation format.
These annotations do not extend any of the classes in the scala.annotation package, but can generally be used in the same way as Scala annotations.
The host platform may impose additional restrictions on the expressions which are valid as annotation arguments.


Spec 12 The Scala Standard Library (`docs/_spec/12-the-scala-standard-library.md`)


title: Standard Library layout: default chapter: 12

The Scala Standard Library

The Scala standard library consists of the package scala with a number of classes and modules.
Some of these classes are described in the following.

Fundamental Type Aliases

The scala package provides the following fundamental type aliases, which expose to user code some forms of types that cannot otherwise be written:

scala
type AnyKind = ´x´           // where ´x´ is the internal AnyKind type
type Nothing = ´x´           // where ´x´ is the internal Nothing type
type | = [A, B] =>> A ´|´ B // where | is the internal union type operator
type & = [A, B] =>> A ´&´ B // where & is the internal intersection type operator

Root Classes

The root of this hierarchy is formed by class scala.Any.
Every class in a Scala execution environment inherits directly or indirectly from this class.
By definition, Any is also the top proper type.
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.
Classes written in other languages inherit from scala.AnyRef.

The predefined subclasses of class AnyVal describe values which are not implemented as objects in the underlying host system.

User-defined Scala classes which do not explicitly inherit from AnyVal inherit directly or indirectly from AnyRef.
They cannot inherit from both AnyRef and AnyVal.

Classes AnyRef and AnyVal are required to provide only the members declared in class Any, but implementations may add host-specific methods to these classes (for instance, 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.

scala
package scala
/** The universal root class */
abstract class Any {

  /** Defined equality; abstract here */
  def equals(that: Any): Boolean

  /** 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
}

/** 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 that
  final def eq(that: AnyRef): Boolean = ... // reference equality
  final def ne(that: AnyRef): Boolean = !(this eq that)

  def hashCode: Int = ...     // hashCode computed from allocation address
  def toString: String  = ... // toString computed from hashCode and class name

  def synchronized[T](body: => T): T // execute `body` in while locking `this`.
}

The type test ´x´.isInstanceOf[´T´] is equivalent to a typed pattern match

scala
´x´ match {
  case _: ´T'´ => true
  case _ => false
}

where the type ´T'´ is the same as ´T´ except if ´T´ is of the form ´D´ or ´D[\mathit{tps}]´ where ´D´ is a type member of some outer class ´C´.
In this case ´T'´ is ´C´#´D´ (or ´C´#´D[tps]´, respectively), whereas ´T´ itself would expand to ´C´.this.´D[tps]´.
In other words, an isInstanceOf test does not check that types have the same enclosing instance.

The test ´x´.asInstanceOf[´T´] is treated specially if ´T´ is a numeric value type.
In this case the cast will be translated to an application of a conversion method x.to´T´.
For non-numeric values ´x´ the operation will raise a ClassCastException.

Value Classes

Value classes are classes whose instances are not represented as objects by the underlying host system.
All value classes inherit from class AnyVal.
Scala implementations 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 of these classes are defined in the following.

Numeric Value Types

Classes Double, Float, Long, Int, Char, Short, and Byte are together called numeric value 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 called floating point types.

Numeric value types are ranked in the following partial order:

scala
Byte - Short
             \
               Int - Long - Float - Double
             /
        Char

Byte and Short are the lowest-ranked types in this order, whereas Double is the highest-ranked.
Ranking does not
imply a conformance relationship; for instance Int is not a subtype of Long.
However, object Predef defines views 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.

Given two numeric value types ´S´ and ´T´, the operation type of ´S´ and ´T´ is defined as follows: 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 operation type 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 exist in 7 overloaded alternatives.
    Each alternative takes a parameter of some numeric value type.
    Its result type is type Boolean.
    The operation is evaluated 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 is the operation type of ´T´ and ´U´.
    The operation is evaluated by converting the receiver and its argument to their operation type and performing the given arithmetic operation of that type.
  • Parameterless arithmetic methods identity (+) and negation (-), with result type ´T´.
    The first of these returns the receiver unchanged, whereas the second returns its negation.
  • Conversion methods toByte, toShort, toChar, toInt, toLong, toFloat, toDouble which convert the receiver object to the target type, using the rules of Java's numeric type cast operation.
    The conversion might truncate the numeric 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 between 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 alternative takes a parameter of some integer numeric value type.
    Its result type is the operation type of ´T´ and ´U´.
    The operation is evaluated by converting the receiver and its argument to their operation type and performing the given bitwise operation of that type.

  • A parameterless bit-negation method (~).
    Its result type is the receiver type ´T´ or Int, whichever is larger.
    The operation is evaluated by converting the receiver to 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 of the 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 the specified shift by ´n´ bits.

Numeric value types also implement operations equals, hashCode, and toString from class Any.

The equals method tests whether the argument is a numeric value type.
If this is true, it will perform the == operation which is appropriate for that type.
That is, the equals method of a numeric value type can be thought of being defined as follows:

scala
def equals(other: Any): Boolean = other match {
  case that: Byte   => this == that
  case that: Short  => this == that
  case that: Char   => this == that
  case that: Int    => this == that
  case that: Long   => this == that
  case that: Float  => this == that
  case that: Double => this == that
  case _ => false
}

The hashCode method returns an integer hashcode that maps equal numeric values to equal results.
It is guaranteed to be the identity for type Int and for all subrange types.

The toString method displays its receiver as an integer or floating point number.

Example

This is the signature of the numeric value type Int:

text
/* Detailed source-code truncated for AI context efficiency. */

Class `Boolean`

Class Boolean has only two values: true and false.
It implements operations as given in the following class definition.

scala
package scala
abstract sealed class Boolean extends AnyVal {
  def && (p: => Boolean): Boolean = // boolean and
    if (this) p else false
  def || (p: => Boolean): Boolean = // boolean or
    if (this) true else p
  def &  (x: Boolean): Boolean =    // boolean strict and
    if (this) x else false
  def |  (x: Boolean): Boolean =    // boolean strict or
    if (this) true else x
  def == (x: Boolean): Boolean =    // boolean equality
    if (this) x else x.unary_!
  def != (x: Boolean): Boolean =    // boolean inequality
    if (this) x.unary_! else x
  def unary_!: Boolean =            // boolean negation
    if (this) false else true
}

The class also implements operations equals, hashCode, and toString from class Any.

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 receiver converted to a string, i.e. either "true" or "false".

Class `Unit`

Class 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 otherwise.
The hashCode method returns a fixed, implementation-specific hash-code.
The toString method returns "()".

Standard Reference Classes

This section presents some standard Scala reference classes which are treated in a special way by the Scala compiler – either Scala provides syntactic sugar for them, or the Scala compiler generates special code for their operations.
Other classes in the standard Scala library are documented in the Scala library documentation by HTML pages.

Class `String`

Scala's String class is usually derived from the standard String class of the underlying host system (and may be identified with it).
For Scala clients the class is taken to support in each case a method

scala
def + (that: Any): String

which concatenates its left operand with the textual representation of its right operand.

The `Function` Classes

For each natural ´n \geq 0´, the scala package defines the following function class:

scala
package scala
trait Function´_n´[-´T_1´, ..., -´T_n´, +´R´]:
  def apply(´x_1´: ´T_1´, ..., ´x_n´: ´T_n´): ´R´

These classes participate in the desugaring of concrete function types.

For values of ´n \leq 22´, the Function´_n´ classes define additional methods:

scala
package scala
trait Function´_n´[-´T_1´, ..., -´T_n´, +´R´]:
  ...
  override def toString = "<function´_n´>"
  def curried: ´T_1´ => ... => ´T_n´ => R = ...
  def tupled: ((´T_1´, ..., ´T_n´)) => R = ...

The implicitly imported Predef object defines the name
Function as an alias of Function1.

The PartialFunction subclass of Function1 represents functions that (indirectly) specify their domain.
Use the isDefined method to query whether the partial function is defined for a given input (i.e., whether the input is part of the function's domain).

scala
class PartialFunction[-A, +B] extends Function1[A, B] {
  def isDefinedAt(x: A): Boolean

  ... // various derived methods
}

PartialFunction participates in the desugaring of pattern matching anonymous functions.

Trait `Product`

All case classes automatically extend the Product trait (and generate synthetic methods to conform to it) (but not Product´n´), and define a _´n´ method for each of their arguments.

Trait `Enum`

All enum definitions automatically extend the reflect.Enum trait (and generate synthetic methods to conform to it).

Tuple Classes

Tuples are a form of HLists defined by the following classes:

scala
/** Superclass of all tuples. */
sealed trait Tuple extends Product:
  /** Return a new tuple by prepending the element to `this` tuple. */
  inline def *: [H, This >: this.type <: Tuple] (x: H): H *: This = ...
  ...

object Tuple:
  /** Type of the element at position N in the tuple X. */
  type Elem[X <: Tuple, N <: Int] = ...
  ...

/** A tuple of 0 elements. */
type EmptyTuple = EmptyTuple.type

/** A tuple of 0 elements. */
case object EmptyTuple extends Tuple:
  override def toString(): String = "()"

/** Tuple of arbitrary non-zero arity */
sealed trait NonEmptyTuple extends Tuple:
  /** Get the i-th element of this tuple. */
  inline def apply[This >: this.type <: NonEmptyTuple](n: Int): Elem[This, n.type] = ...
  ...

sealed abstract class *:[+H, +T <: Tuple] extends NonEmptyTuple

object `*:` :
  def unapply[H, T <: Tuple](x: H *: T): (H, T) = (x.head, x.tail)

For ´1 \leq n \leq 22´, the concrete implementations of *: are instances of Tuple´_n´ classes, which also implement corresponding Product´_n´ traits.
They are defined at least as follows in the standard Scala library (they might also add other methods and implement other traits).

scala
trait Product´_n´[+´T_1´, ..., +´T_n´] extends Product:
  override def productArity: Int = ´n´
  def _1: ´T_1´
  ...
  def _n: ´T_n´

final case class Tuple´_n´[+´T_1´, ..., +´T_n´](_1: ´T_1´, ..., _n: ´T_n´)
    extends *:[´T_1´, ´T_2´ *: ... _: ´T_n´ *: EmptyTuple]
    with Product´_n´[´T_1´, ..., ´T_n´]

For ´n > 22´, the concrete implementations of ´*:´ are instances of implementation-specific private classes.

Class `Array`

All operations on arrays desugar to the corresponding operations of the underlying platform.
Therefore, the following class definition is given for informational purposes only:

scala
final class Array[T](_length: Int)
extends java.io.Serializable with java.lang.Cloneable {
  def length: Int = ...
  def apply(i: Int): T = ...
  def update(i: Int, x: T): Unit = ...
  override def clone(): Array[T] = ...
}

If ´T´ is not a type parameter or abstract type, the type Array[T] is represented as the array type |T|[] in the underlying host system, where |T| is the erasure of T.
If ´T´ is a type parameter or abstract type, a different representation might be used (it is Object on the Java platform).

Operations

length returns the length of the array, apply means subscripting, and update means element update.

Because of the syntactic sugar for apply and update operations, we have the following correspondences between Scala and Java code for operations on an array xs:

Scala Java
xs.length xs.length
xs(i) xs[i]
xs(i) = e xs[i] = e

Two implicit conversions exist in Predef that are frequently applied to arrays: a conversion to scala.collection.mutable.ArrayOps and a conversion to scala.collection.mutable.ArraySeq (a subtype of scala.collection.Seq).

Both types make many of the standard operations found in the Scala collections API available.
The conversion to ArrayOps is temporary, as all operations defined on ArrayOps return a value of type Array, while the conversion to ArraySeq is permanent as all operations return a value of type ArraySeq.
The conversion to ArrayOps takes priority over the conversion to ArraySeq.

Because of the tension between parametrized types in Scala and the ad-hoc implementation of arrays in the host-languages, some subtle points need to be taken into account when dealing with arrays.
These are explained in the following.

Variance

Unlike arrays in Java, arrays in Scala are not co-variant; That is, ´S <: T´ does not imply Array[´S´] ´<:´ Array[´T´] in Scala.
However, it is possible to cast an array 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 though String conforms to Object.
However, it is possible to cast an expression of type Array[String] to Array[Object], and this cast will succeed without raising a ClassCastException. Example:

scala
val xs = new Array[String](2)
// val ys: Array[Object] = xs   // **** error: incompatible types
val ys: Array[Object] = xs.asInstanceOf[Array[Object]] // OK

The instantiation of an array with a polymorphic element type ´T´ requires information about type ´T´ at runtime.
This information is synthesized by adding a context bound of scala.reflect.ClassTag to type ´T´.
An example is the following implementation of method mkArray, which creates an array of an arbitrary type ´T´, given a sequence of ´T´`s which defines its elements:

scala
import reflect.ClassTag
def mkArray[T : ClassTag](elems: Seq[T]): Array[T] = {
  val result = new Array[T](elems.length)
  var i = 0
  for (elem <- elems) {
    result(i) = elem
    i += 1
  }
  result
}

If type ´T´ is a type for which the host platform offers a specialized array representation, this representation is used.

Example

On the Java Virtual Machine, an invocation of mkArray(List(1,2,3)) will return a primitive array of ints, written as int[] in Java.

Companion object

Array's companion object provides various factory methods for the instantiation of single- and multi-dimensional arrays, an extractor method unapplySeq which enables pattern matching over arrays and additional utility methods:

text
/* Detailed source-code truncated for AI context efficiency. */

Class Node

text
/* Detailed source-code truncated for AI context efficiency. */

The `Predef` Object

The Predef object defines standard methods and type aliases for Scala programs.
It is implicitly imported, as described in the chapter on name binding, so that all its defined members are available without qualification.
Its definition for the JVM environment conforms to the following signature:

text
/* Detailed source-code truncated for AI context efficiency. */
scala
// 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: _*))

  // Implicit conversions ------------------------------------------------

  ...
}

Predefined Implicit Definitions

The Predef object also contains a number of implicit definitions, which are available by default (because Predef is implicitly imported).
Implicit definitions come in two priorities.
High-priority implicits are defined in the Predef class itself whereas low priority implicits are defined in a class inherited by Predef.
The rules of static overloading resolution 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 categories.

  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 implicitly converted 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 ArraySeq class.
    For instance, values of type Array[Float] can be implicitly converted to instances of class ArraySeq[Float].
    There are also generic array wrappers that take elements of type Array[T] for arbitrary T to ArraySeqs.

  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 overloaded variants to type Any.
scala
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.
scala
def -> [B](y: B): (A, B) = (x, y)
  • For every array type with elements of primitive type, a wrapper that takes the arrays of that type to instances of a runtime.ArrayOps class.
    For instance, values of type Array[Float] can be implicitly converted to instances of class runtime.ArrayOps[Float].
    There are also generic array wrappers that take elements of type Array[T] for arbitrary T to ArrayOpss.

  • An implicit wrapper that adds + and formatted method with the following implementations to type Any.

scala
def +(other: String) = String.valueOf(self) + other
def formatted(fmtstr: String): String = fmtstr format self
  • Numeric primitive conversions that implement the transitive closure of the following mappings:
text
Byte  -> Short
Short -> Int
Char  -> Int
Int   -> Long
Long  -> Float
Float -> Double
  • Boxing and unboxing conversions between primitive types and their boxed versions:
text
Byte    <-> java.lang.Byte
Short   <-> java.lang.Short
Char    <-> java.lang.Character
Int     <-> java.lang.Integer
Long    <-> java.lang.Long
Float   <-> java.lang.Float
Double  <-> 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.
scala
sealed abstract class <:<[-From, +To] extends (From => To)

Implicit parameters of <:< types are typically used to implement type constraints.


Spec 13 Syntax Summary (`docs/_spec/13-syntax-summary.md`)


title: Syntax Summary layout: default chapter: 13

Syntax Summary

The following descriptions of Scala tokens uses literal characters ‘c’ when referring to the ASCII fragment \u0000 – \u007F.

Informal descriptions are typeset as “some comment”.

Lexical Syntax

The lexical syntax of Scala is given by the following grammar in EBNF form:

text
/* Detailed source-code truncated for AI context efficiency. */

Optional Braces

text
colon         ::=  ':'    -- with side conditions explained in 01-literal-syntax.md
 <<< ts >>>   ::=  ‘{’ ts ‘}’
                |  indent ts outdent
:<<< ts >>>   ::=  [nl] ‘{’ ts ‘}’
                |  colon indent ts outdent

Context-free Syntax

´\color{red}{\text{TODO SCALA3: Once we're done porting the spec, make sure that
the references to grammar productions in the rest of the spec match this.}}´

The context-free syntax of Scala is given by the following EBNF grammar:

text
/* Detailed source-code truncated for AI context efficiency. */

Spec A1 Deprecated (`docs/_spec/A1-deprecated.md`)

Symbol Literals

Symbol literals are no longer supported.

The scala.Symbol class still exists, so a literal translation of the symbol literal 'xyz is Symbol("xyz"). However, it is recommended to use a plain string literal "xyz" instead. (The Symbol class will be deprecated and removed in the future). Example:

text
scalac Test.scala
-- Error: Test.scala:1:25 ------------------------------------------------------------------------------------------------

1 |@main def test = println('abc)
  |                         ^
  |                         symbol literal 'abc is no longer supported,
  |                         use a string literal "abc" or an application Symbol("abc") instead,
  |                         or enclose in braces '{abc} if you want a quoted expression.
  |                         For now, you can also `import language.deprecated.symbolLiterals` to accept
  |                         the idiom, but this possibility might no longer be available in the future.
1 error found

Spec A2 Scala 2 Compatibility (`docs/_spec/A2-scala-2-compatibility.md`)

Existential Types

Existential types using forSome (as in SLS §3.2.12) are not available in Scala 3.
Therefore when reading an existential type from Scala 2, the following happens:

Existential types that can be expressed using only wildcards (but not
forSome) are treated as refined types.
For instance, the type

scala
Map[_ <: AnyRef, Int]

is treated as the type Map, where the first type parameter
is upper-bounded by AnyRef and the second type parameter is an alias
of Int.

When reading class files compiled with Scala 2, Scala 3 will do a best
effort to approximate existential types with its own types. It will
issue a warning that a precise emulation is not possible.

Procedure Syntax

Procedure syntax

scala
def f() { ... }

has been dropped. You need to write one of the following instead:

scala
def f() = { ... }
def f(): Unit = { ... }

Scala 3 accepts the old syntax under the -source:3.0-migration option.
If the -migration option is set, it can even rewrite old syntax to new.
The Scalafix tool also
can rewrite procedure syntax to make it Scala 3 compatible.

Compound Types (`with`)

Intersection types A & B replace compound types A with B in Scala 2.
For the moment, the syntax A with B is still allowed and interpreted as A & B, but its usage as a type (as opposed to in a new or extends clause) will be deprecated and removed in the future.


Spec A3 To Be Deprecated (`docs/_spec/A3-to-be-deprecated.md`)

This is a simple list of feature that are not deprecated yet, but will be in the future.
They should emit warnings or errors only when using the -source:future compiler flag.


Spec Config.Yml (`docs/_spec/_config.yml`)

baseurl: /files/archive/spec/3.4
latestScalaVersion: 3.4
thisScalaVersion: 3.4
versionCompareMessage: "an upcoming"
safe: true
lsi: false
highlighter: false
encoding: utf-8
exclude:

  • APPLIEDreference
  • TODOreference
  • docker-compose.yml
  • Dockerfile
  • Gemfile
  • Gemfile.lock
  • README.md
  • spec-toc.xslt
  • package.json
  • package-lock.json
  • node_modules

Spec Docker Compose.Yml (`docs/_spec/docker-compose.yml`)

services:
jekyll:
user: "${UID}:${GID}"
build: .
command: sh -c "chown $UID / && bundle exec jekyll serve --incremental --host=0.0.0.0"
ports:
- '4000:4000'
volumes:
- .:/srv/jekyll


Scaladoc Testcases Docs Sidebar.Yml (`scaladoc-testcases/docs/sidebar.yml`)

index: index.md
subsection:

  • page: docs/f1.md
  • page: docs/f2.md
  • page: docs/f3.md
  • page: docs/f4.md
  • page: docs/f5.html

.Ai Skills Add Error Code Docs (`docs/.ai/skills/add-error-code-docs.md`)

Add Error Code Docs

Canonical skill for creating or updating Scala 3 error-code docs in
docs/_docs/reference/error-codes/.

This file is the single source of truth. Keep other related files as pointers.

Best-Effort Contract

  • Prefer full mechanical validation with project/scripts/checkErrorCodeSnippets.scala.
  • If the environment blocks full validation, still produce the best draft possible and
    clearly mark what was not verified.
  • If a code is not reproducible from pure Scala snippets, follow the non-reproducible path
    below and keep NonReproducibleErrorCodes aligned in
    project/scripts/checkErrorCodeSnippets.scala.

Required Output Shape

Use this template for each E###.md page:

markdown
---
title: E###: <Short Title>
kind: Error
# since: 3.x.y   # required when code > E166
# until: 3.x.y   # required when the compiler ID is inactive
---
# E###: <Short Title>

<Explain when this diagnostic happens and why.>

## Example

```scala sc:fail sc-opts:-explain
<minimal snippet that triggers only E###>
```

### Error

```scala sc:nocompile
-- [E###] <Error|Warning>: example.scala:<line>:<col> -------------------------
<exact checker output here, including explanation text when present>
```

### Solution

```scala sc:compile
<direct fix of the example above>
```


<aside class="warning">
    This reference page was created with LLM assistance - the description of the error code may not be accurate or cover all possible scenarios.
</aside>

For warning diagnostics, normally make the example fail under -Werror:

scala sc:fail sc-opts:-werror
<warning-producing snippet>

Workflow

  1. Establish target metadata.
  • Find the compiler ID in compiler/src/dotty/tools/dotc/reporting/ErrorMessageID.scala.
  • Use filename docs/_docs/reference/error-codes/E###.md.
  • Set frontmatter title and kind (Error or Warning).
  • Add since when errorNumber > 166.
  • Add until when the ID is inactive.
  1. Draft from a nearby entry.
  • Keep section order: ## Example, ### Error or ### Warning, ### Solution.
  • Keep snippets minimal and deterministic.
  • Keep solutions as direct fixes of the failing scenario.
  1. Apply snippet marker rules.
  • Example: sc:fail (or custom-sc:fail only when required).
  • Output block: sc:nocompile.
  • Solution: sc:compile (or custom-sc:compile only when required).
  • Include needed flags in snippet options (sc-opts:-explain, sc-opts:-Werror, etc.).
  1. Keep output faithful.
  • Store exact compiler output with [E###].
  • Include explain text when emitted.
  1. Keep indexing consistent.
  • Add new files to docs/sidebar.yml under Error Codes in numeric order.

Validation Commands

From repository root:

bash
DOC=docs/_docs/reference/error-codes/E###.md

One-time local compiler setup (rerun only when artifacts/version change):

bash
sbtn scala3-bootstrapped/publishLocal

Cache local bootstrapped version:

bash
VERSION_CACHE=/tmp/scala3-bootstrapped-version.txt
version=$(BOOTSTRAPPED_VERSION_CACHE="$VERSION_CACHE" project/scripts/get-bootstrapped-version.sh --refresh)
# later runs:
# version=$(BOOTSTRAPPED_VERSION_CACHE="$VERSION_CACHE" project/scripts/get-bootstrapped-version.sh)

Refresh ### Error / ### Warning output:

bash
scala --server=false --scala-version "$version" \
  project/scripts/checkErrorCodeSnippets.scala -- "$DOC" --update-output

Run full validation:

bash
scala --server=false --scala-version "$version" \
  project/scripts/checkErrorCodeSnippets.scala -- "$DOC" --verbose

Expected guarantees when validation runs:

  • Example snippets fail and include the documented E###.
  • Unexpected extra error codes are rejected.
  • Output block matches compiler output.
  • Solution snippets compile cleanly (-Werror enforced by checker).

Completion Checklist

  • Frontmatter and heading match E###.
  • Examples produce only the documented code (or are explicitly non-reproducible).
  • Output block includes exact checker output.
  • Solutions resolve the same scenario and compile without warnings.
  • Sidebar entry exists and is ordered.

Blog Posts 2015 10 23 Dotty Compiler Bootstraps (`docs/_blog/_posts/2015-10-23-dotty-compiler-bootstraps.md`)


layout: blog-page author: Martin Odersky and Dmitry Petrashko title: "We got liftoff!" subTitle: The Dotty compiler for Scala bootstraps. excerpt_separator: date: 2015-10-23

The Dotty project
is a platform to develop new technology for Scala
tooling and to try out concepts of future Scala language versions.
Its compiler is a new design intended to reflect the
lessons we learned from work with the Scala compiler. A clean redesign
today will let us iterate faster with new ideas in the future.

Today we reached an important milestone: the Dotty compiler can
compile itself, and the compiled compiler can act as a drop-in for the
original one. This is what one calls a bootstrap.

Why is this important?

The main reason is that this gives us a some validation of the
trustworthiness of the compiler itself. Compilers are complex beasts,
and many things can go wrong. By far the worst things that can go
wrong are bugs where incorrect code is produced. It's not fun debugging code that looks perfectly
fine, yet gets translated to something subtly wrong by the compiler.

Having the compiler compile itself is a good test to demonstrate that
the generated code has reached a certain level of quality. Not only is
a compiler a large program (44k lines in the case of Dotty), it is
also one that exercises a large part of the language in quite
intricate ways. Moreover, bugs in the code of a compiler don't tend to
go unnoticed, precisely because every part of a compiler feeds into
other parts and all together are necessary to produce a correct
translation.

Are we done yet?

Far from it! The compiler is still very rough. A lot more work is
needed to

  • make it more robust, in particular when analyzing incorrect programs,
  • improve error messages and warnings,
  • improve the efficiency of some of the generated code,
  • improve compilation speed,
  • embed it in external tools such as sbt, REPL, IDEs,
  • remove restrictions on what Scala code can be compiled,
  • help in migrating Scala code that will have to be changed.

What are the next steps?

Over the coming weeks and months, we plan to work on the following topics:

  • Make snapshot releases.
  • Work on SBT integration of the compiler.
  • Work on IDE support.
  • Investigate the best way to obtaining a REPL.
  • Work on the build infrastructure.

If you want to get your hands dirty with any of this, now is a good
moment to get involved! Join the team of contributors, including
Dmitry Petrashko (@DarkDimius),
Guillaume Martres (@smarter),
Ondrey Lhotak (@olhotak),
Samuel Gruetter (@samuelgruetter),
Vera Salvis (@vsalvis),
and Jason Zaugg (@retronym).

To get started: https://github.com/lampepfl/dotty.


Blog Posts 2016 01 02 New Year Resolutions (`docs/_blog/_posts/2016-01-02-new-year-resolutions.md`)


layout: blog-page title: New Year Resolutions author: Martin Odersky authorImg: images/martin.jpg date: 2016-01-02

For most of us, the change of the year is an occasion for thinking
about what we missed doing last year and where we want to improve. I decided
there are a couple of things where I would like to do better in 2016
than in 2015. The first is that I would like to do more blogging and
writing in general. I have been pretty silent for most of the last
year. This was mostly caused by the fact that I had been heads down to
work on DOT, Scala's foundations, and Dotty, the new Scala compiler
platform we are working on. It's been a lot of work, but we are finally
getting good results. DOT now has a mechanized proof of type soundness
and the Dotty compiler can now compile
itself

as well as large parts of Scala's standard library.

The Dotty compiler has a completely new and quite unusual
architecture, which makes it resemble a functional database or a
functional reactive program. My talk at the JVM language
summit
gives an
overview. In the coming months I want to write together with my
collaborators a series of blog posts
that explain details of the code base. The
aim of these posts will be to present the new architectural patterns
to a larger audience and also to help existing and potential
contributors get familiar with the code base.

My second resolution is to take a larger effort to promote simplicity
in Scala. I believe the recent blog post by Jim
Plush
should be a wakeup call for our
community. Scala is a very powerful and un-opinionated language. This
means we have a large spectrum of choice how to write a Scala
application or library. It's very important for all of us to use this
power wisely, and to promote simplicity of usage wherever possible.
Unfortunately, most of us fall all too easily into the complexity
trap, as Alex Payne's tweet sums it up very nicely.

“Complexity is like a bug light for smart people. We can't resist it, even though we know it's bad for us.” https://t.co/V9Izi573CF— Alex Payne (@al3x) January 1, 2016

I have been as guilty of complication as everybody else. Is
CanBuildFrom the most appropriate solution to deal with the
constraints of embedding special types such as arrays and strings in a
collection library? It achieves its purpose of providing a uniform
user-level API on disparate datatypes. But I now think with more
effort we might be able come up with a solution that works as well and
is simpler. Another example, where I have doubts if not regrets are
the /: and :\ operators in scala.collections. They are cute
synonyms for folds, and I am still fond of the analogy with falling
dominoes they evoke. But in retrospect I think maybe they did give a
bad example for others to go overboard with symbolic operators.

So my main agenda for the coming year is to work on making Scala
simpler: The language, its foundations, its libraries. I hope you
will join me in that venture.

With that thought, I wish you a happy new year 2016.


Blog Posts 2016 02 03 Essence Of Scala (`docs/_blog/_posts/2016-02-03-essence-of-scala.md`)


layout: blog-page title: The Essence of Scala author: Martin Odersky authorImg: images/martin.jpg date: 2016-02-03

What do you get if you boil Scala on a slow flame and wait until all
incidental features evaporate and only the most concentrated essence
remains? After doing this for 8 years we believe we have the answer:
it's DOT, the calculus of dependent object types, that underlies Scala.

A paper on DOT will be
presented in April at Wadlerfest,
an event celebrating Phil Wadler's 60th birthday. There's also a prior
technical report (From F to DOT)
by Tiark Rompf and Nada Amin describing a slightly different version
of the calculus. Each paper describes a proof of type soundness that
has been machine-checked for correctness.

The DOT calculus

A calculus is a kind of mini-language that is small enough to be
studied formally. Translated to Scala notation, the language covered
by DOT is described by the following abstract grammar:

text
Value       v  =  (x: T) => t            Function
                  new { x: T => ds }     Object

Definition  d  =  def a = t              Method definition
                  type A = T             Type

Term        t  =  v                      Value
                  x                      Variable
                  t1(t2)                 Application
                  t.a                    Selection
                  { val x = t1; t2 }     Local definition

Type        T  =  Any                    Top type
                  Nothing                Bottom type
                  x.A                    Selection
                  (x: T1) => T2          Function
                  { def a: T }           Method declaration
                  { type T >: T1 <: T2 } Type declaration
                  T1 & T2                Intersection
                  { x => T }             Recursion

The grammar uses several kinds of names:

text
x      for (immutable) variables
a      for (parameterless) methods
A      for types

The full calculus adds to this syntax formal typing rules that
assign types T to terms t and formal evaluation rules that
describe how a program is evaluated. The following type soundness
property was shown with a mechanized, (i.e. machine-checked) proof:

If a term t has type T, and the evaluation of t terminates, then
the result of the evaluation will be a value v of type T.

Difficulties

Formulating the precise soundness theorem and proving it was unexpectedly hard,
be