Scala 3 Documentation

repository·main·Indexed 27 days ago

https://github.com/scala/scala3

The latest major version of the Scala programming language, including its compiler, standard library, and language specification. This repository contains documentation for the scala3-directives-parser API, build instructions for local distributions and MSI/Chocolatey packages, and changelogs for versions 3.2.1 through 3.4.0-RC1 covering features like Scala.js dynamic imports, reflection API updates, and experimental compiler flags.

Tokens
179.1K
Snippets
537
Records
1K
Agent score
92%

What's inside Scala 3

  1. Overview of Scala 3 Language Feature Classifications

    main

    Scala 3 features are classified into eight categories to help developers understand their impact on the language foundation, migration effort, and usage patterns:

    1. Essential Foundations: Core features modeling DOT, higher-kinded types, and SI calculus (e.g., Intersection types, Union types, Type lambdas, Context functions).
    2. Simplifications: Constructs that replace existing ones to improve safety and uniformity (e.g., Given instances, Using clauses, Extension methods, Opaque type aliases, Top-level definitions).
    3. Restrictions: Changes made to increase language safety (e.g., Implicit Conversions restrictions, Given Imports, Multiversal equality).
    4. Dropped Constructs: Features being removed to simplify the language (e.g., DelayedInit, Existential types, Procedure syntax).
    5. Changes: Refined existing constructs (e.g., Structural Types, Name-based pattern matching, Eta expansion, Implicit Resolution).
    6. New Constructs: Powerful additions (e.g., Enums, Parameter untupling, Dependent function types, Kind polymorphism).
    7. Metaprogramming: Features aimed at replacing existing macros.
    8. Type Checking and Inference: Changes to how types are resolved and inferred.
  2. Understand the Mirror mechanism for type class derivation

    main

    Scala 3 uses a low-level Mirror infrastructure to support type class derivation. Mirror instances are compiler-generated and typically implemented in the companion object of an ADT. The infrastructure consists of two main parts:

    1. Type members: These encode the properties of the mirrored types (e.g., structure, product/sum nature).
    2. Value-level mechanism: A minimal set of methods (like ordinal and fromProduct) for working generically with terms of the mirrored types.

    This design aims to keep the bytecode and runtime footprint small by encoding properties via types rather than terms, allowing Mirror instances to be provided unconditionally.

  3. Understand the Scala 3 Type Hierarchy

    main

    The Scala 3 type system distinguishes between Proxy types and Ground types.

    • Proxy types: Inherit from TypeProxy. They act as a proxy for another type and allow access to the actual type via the underlying method. Examples include NamedType, SingletonType, TypeParamRef, and AppliedType.
    • Ground types: Inherit from CachedGroundType or UncachedGroundType. These represent the actual concrete type structure. Examples include AndType, OrType, MethodType, ClassInfo, and ErrorType.

    Detailed definitions are located in dotty/tools/dotc/core/Types.scala.

  4. Understand Scala 3 Overload Resolution improvements

    main

    Scala 3 introduces three key improvements to how the compiler resolves overloaded methods compared to Scala 2:

    1. Multi-argument list consideration: The compiler now considers all provided argument lists, not just the first one, to resolve ambiguity.
    2. Improved function value inference: The compiler can infer parameter types of function values even when they appear in the first argument list, provided the remaining arguments allow for a unique selection.
    3. Default argument prioritization: Methods with default arguments are no longer deprioritized. In Scala 2, having default arguments could cause a method to be ignored during overload resolution; in Scala 3, they are treated with the same priority as other methods.
  5. Understand Scoped Capabilities and `any`

    main

    In Scala 3's experimental capture checking, any is a universal capability representing a set of capabilities visible at a specific scope. Each occurrence of any represents a different capability. They form a subcapturing hierarchy based on lexical nesting: a nested scope's any subsumes its enclosing scope's any (e.g., {any_outer} <: {any_inner}).

    Key positions for any:

    • Local anys: Every class, method body, and block has its own. They form a hierarchy based on lexical nesting.
    • Parameter anys: Found in function parameters (e.g., def foo(x: T^)). These are instantiated at call sites to the actual capabilities passed.
    • Result anys: Found in function result types (e.g., A^ -> B^). These refer to the local any of the enclosing scope.
    • Result freshs: Found in function result types (e.g., A^ -> B^{fresh}). Unlike any, fresh introduces a new, isolated, existentially bound capability that cannot be merged with the enclosing scope.
    import language.experimental.captureChecking
    import caps.*
  6. Compare Scala Capture Checking with Rust Lifetimes

    main

    Scala's capture checking shares conceptual similarities with Rust's lifetime system, but with different implementation goals:

    ConceptRustScala 3 Capture Checking
    MechanismExplicit lifetime parameters (&'a T)Implicit capability names (T^{x})
    Binding'a is an explicit parameterx's level is computed from program structure
    GoalMemory validity (preventing dangling pointers)Capability usage (preventing unauthorized effects)
    Containment'a: 'b (a outlives b)Level containment (outer scopes flow into inner ones)

    In Scala, a capture set {x, y} acts as an upper bound for a value: the value is only valid as long as all capabilities in its set are visible.

  7. Use Named Tuples in Scala 3.7

    main
    Named Tuples (SIP-58) are now a stable feature in Scala 3.7. They allow for tuples where elements can be accessed by name, improving code readability and providing better support for pattern matching and mirrors.
  8. Understanding Contextual Abstractions in Scala 3

    main
    Scala 3 introduces a redesigned approach to contextual abstractions to address the complexities and potential abuses of Scala 2's implicit system. The new design aims to distinguish between different intents (such as type class instances vs. implicit conversions) and provides clearer syntax for implicit parameters and imports. This helps prevent common issues like inscrutable type errors, accidental implicit conversions, and confusing method call syntax.
  9. Metaprogramming in Scala 3

    main

    Scala 3 introduces a new foundation for metaprogramming to replace the fragile macro mechanisms used in Scala 2. Instead of relying on compiler-internal macros, Scala 3 provides several advanced language constructs designed to be more robust and principled.

    Key metaprogramming features include:

    • Match types: Allow for computation on types.
    • Inline: Provides a straightforward implementation for simple macros and serves as a building block for complex ones.
    • Quotes and splices: A unified set of abstractions for expressing macros and staging.
    • Type class derivation: An in-language implementation for deriving type classes (replacing the need for libraries like Shapeless Gen).
    • Implicit by-name parameters: Provides a robust implementation for lazy evaluation (replacing the need for libraries like Shapeless Lazy).

    Note: These features are designed to replace existing macro-based libraries, which may require significant rewrites when migrating from Scala 2.

  10. Understand statements in blocks and templates

    main

    Statements occur within blocks and templates. A statement can be an import, a definition (local or template), or an expression.

    • Expression Statements: An expression used as a statement is evaluated, and its result is discarded.
    • Block-local Definitions: Definitions in a block can bind local names. The only allowed modifier for block-local definitions is implicit. For class or object definitions, abstract, final, and sealed are also permitted.
    • Sequence Evaluation: A sequence of statements is evaluated in the order they are written.
  11. Core Foundations of Scala 3

    main

    Scala 3 introduces several essential foundational constructs that model core features like higher-kinded types and the DOT calculus. These are considered core to the language and generally have low migration costs as they are additions to the language.

    Key foundational features include:

    • Intersection types: Replaces compound types.
    • Union types
    • Type lambdas: Replaces encodings using structural types and type projection.
    • Context functions: Provides abstraction over given parameters.