|  | 
|  | 1 | +--- | 
|  | 2 | +layout: doc-page | 
|  | 3 | +title: "Toplevel Definitions" | 
|  | 4 | +nightlyOf: https://docs.scala-lang.org/scala3/reference/dropped-features/toplevel-definitions.html | 
|  | 5 | +--- | 
|  | 6 | + | 
|  | 7 | +All kind of definitions can now be written at the top-level. | 
|  | 8 | +Example: | 
|  | 9 | +```scala | 
|  | 10 | +package p | 
|  | 11 | +type Labelled[T] = (String, T) | 
|  | 12 | +val a: Labelled[Int] = ("count", 1) | 
|  | 13 | +def b = a._2 | 
|  | 14 | + | 
|  | 15 | +case class C() | 
|  | 16 | + | 
|  | 17 | +extension (x: C) def pair(y: C) = (x, y) | 
|  | 18 | +``` | 
|  | 19 | +Previously, `type`, `val` or `def` definitions had to be wrapped in a package object. Now, | 
|  | 20 | +there may be several source files in a package containing such top-level definitions, and source files can freely mix top-level value, method, and type definitions with classes and objects. | 
|  | 21 | + | 
|  | 22 | +The compiler generates synthetic objects that wrap top-level definitions falling into one of the following categories: | 
|  | 23 | + | 
|  | 24 | + - all pattern, value, method, and type definitions, | 
|  | 25 | + - implicit classes and objects, | 
|  | 26 | + - companion objects of opaque type aliases. | 
|  | 27 | + | 
|  | 28 | +If a source file `src.scala` contains such top-level definitions, they will be put in a synthetic object named `src$package`. The wrapping is transparent, however. The definitions in `src` can still be accessed as members of the enclosing package. The synthetic object will be placed last in the file, | 
|  | 29 | +after any other package clauses, imports, or object and class definitions. | 
|  | 30 | + | 
|  | 31 | +**Note:** This means that | 
|  | 32 | +1. The name of a source file containing wrapped top-level definitions is relevant for binary compatibility. If the name changes, so does the name of the generated object and its class. | 
|  | 33 | + | 
|  | 34 | +2. A top-level main method `def main(args: Array[String]): Unit = ...` is wrapped as any other method. If it appears | 
|  | 35 | +in a source file `src.scala`, it could be invoked from the command line using a command like `scala src$package`. Since the | 
|  | 36 | +"program name" is mangled it is recommended to always put `main` methods in explicitly named objects. | 
|  | 37 | + | 
|  | 38 | +3. The notion of `private` is independent of whether a definition is wrapped or not. A `private` top-level definition is always visible from everywhere in the enclosing package. | 
|  | 39 | + | 
|  | 40 | +4. If several top-level definitions are overloaded variants with the same name, | 
|  | 41 | +they must all come from the same source file. | 
0 commit comments