### Unsafe Resource Management Example in Scala Source: https://docs.scala-lang.org/scala3/reference/experimental/capture-checking/basics.html Demonstrates an unsafe implementation of a try-with-resources pattern using `usingLogFile`. This example highlights how a delayed operation can lead to an `IOException` by attempting to write to a closed file. ```scala def usingLogFile[T](op: FileOutputStream => T): T = val logFile = FileOutputStream("log") val result = op(logFile) logFile.close() result val later = usingLogFile { file => () => file.write(0) } later() // crash ``` -------------------------------- ### Scala 3 Named Tuples: Pattern Matching Examples Source: https://docs.scala-lang.org/scala3/reference/other-new-features/named-tuples.html Provides examples of pattern matching on named tuples, showcasing how patterns can be named or unnamed, and can include a subset of the tuple's names in any order. ```scala Bob match case (name, age) => ... Bob match case (name = x, age = y) => ... Bob match case (age = x) => ... Bob match case (age = x, name = y) => ... ``` -------------------------------- ### Export Clause Elaboration Examples Source: https://docs.scala-lang.org/scala3/reference/other-new-features/export.html Examples demonstrating potential ambiguity in export clause ordering within Scala 3 classes. These snippets illustrate scenarios where the order of export declarations impacts visibility and legality. ```scala class B { val c: Int } object A { val b = new B } export A.* export b.* ``` ```scala export b.* export A.* ``` -------------------------------- ### Scala 3 Context Function Literal Examples Source: https://docs.scala-lang.org/scala3/reference/contextual/context-functions.html Provides examples of context function literals using the '?=>' arrow. It shows how these literals are expanded when passed as arguments to functions expecting context function types. ```scala def g(arg: Executable[Int]) = ... g(22) // is expanded to g((ev: ExecutionContext) ?=> 22) g(f(2)) // is expanded to g((ev: ExecutionContext) ?=> f(2)(using ev)) g((ctx: ExecutionContext) ?=> f(3)) // is expanded to g((ctx: ExecutionContext) ?=> f(3)(using ctx)) g((ctx: ExecutionContext) ?=> f(3)(using ctx)) // is left as it is ``` -------------------------------- ### Scala 3 Method Application and Inference Example Source: https://docs.scala-lang.org/scala3/reference/other-new-features/generalized-method-syntax.html Explains method application in Scala 3, noting that inference applies to rightmost type clauses when not all are explicitly provided. Includes an example demonstrating a type error due to incorrect bounds. ```scala def triple[I <: Int](using Ordering[I])[C <: Char](a: I, b: C) = ??? triple[Char](0, 'c') // error: Char does not conform to upperbound Int ``` -------------------------------- ### Scala 3 Extension Method Syntax Example Source: https://docs.scala-lang.org/scala3/reference/other-new-features/generalized-method-syntax.html Presents the syntax for extension methods in Scala 3, showing how they can incorporate multiple type clauses, similar to regular methods. ```scala extension [T](l1: List[T]) def zipWith[U](l2: List[U])[V](l3: List[V]): List[(T,U,V)] ``` -------------------------------- ### Example Mirror Instances for Tree ADT in Scala 3 Source: https://docs.scala-lang.org/scala3/reference/contextual/derivation.html Illustrates the manual implementation of `Mirror.Sum` for the `Tree` type and `Mirror.Product` for its `Branch` and `Leaf` cases. These examples show how to define the type members and implement the required methods (`ordinal` and `fromProduct`). ```scala // Mirror for Tree new Mirror.Sum: type MirroredType = Tree type MirroredElemTypes[T] = (Branch[T], Leaf[T]) type MirroredMonoType = Tree[_] type MirroredLabel = "Tree" type MirroredElemLabels = ("Branch", "Leaf") def ordinal(x: MirroredMonoType): Int = x match case _: Branch[_] => 0 case _: Leaf[_] => 1 // Mirror for Branch new Mirror.Product: type MirroredType = Branch type MirroredElemTypes[T] = (Tree[T], Tree[T]) type MirroredMonoType = Branch[_] type MirroredLabel = "Branch" type MirroredElemLabels = ("left", "right") def fromProduct(p: Product): MirroredMonoType = new Branch(...) // Mirror for Leaf new Mirror.Product: type MirroredType = Leaf type MirroredElemTypes[T] = Tuple1[T] type MirroredMonoType = Leaf[_] type MirroredLabel = "Leaf" type MirroredElemLabels = Tuple1["elem"] def fromProduct(p: Product): MirroredMonoType = new Leaf(...) ``` -------------------------------- ### Experimental Definitions in Scala 3: RHS Scope Example 2 Source: https://docs.scala-lang.org/scala3/reference/other-new-features/experimental-defs.html Provides a second example for experimental definitions on the RHS, showcasing the use of `@experimental` with `val`, `def`, and `object`. It highlights errors when referencing experimental definitions in a non-experimental context and successful referencing within an experimental context. ```scala import scala.annotation.experimental @experimental val x = () @experimental def f() = () @experimental object X: def fx() = 1 def test1: Unit = f() // error: def f is marked @experimental and therefore ... x // error: value x is marked @experimental and therefore ... X.fx() // error: object X is marked @experimental and therefore ... import X.fx fx() // error: object X is marked @experimental and therefore ... @experimental def test2: Unit = // references to f, x and X are ok because `test2` is experimental f() x X.fx() import X.fx fx() ``` -------------------------------- ### Implement implicit conversion Source: https://docs.scala-lang.org/scala3/reference/contextual/conversions.html Examples of defining implicit conversions from one type to another, including concise syntax using aliases. ```scala given Conversion[String, Token]: def apply(str: String): Token = new KeyWord(str) // Concise alias syntax given Conversion[String, Token] = new KeyWord(_) ``` -------------------------------- ### Basic Context Bound Example in Scala Source: https://docs.scala-lang.org/scala3/reference/contextual/context-bounds.html Demonstrates the basic syntax of a context bound `: Ord` on a type parameter `T` for a `maximum` function. This is a shorthand for a `using` clause. ```scala def maximum[T: Ord](xs: List[T]): T = xs.reduceLeft(max) ``` ```scala def maximum[T](xs: List[T])(using Ord[T]): T = ... ``` -------------------------------- ### Scala 3 Macro Syntax Examples Source: https://docs.scala-lang.org/scala3/reference/metaprogramming/macros-spec.html Demonstrates the syntax for string interpolation and macro quotation in Scala 3, highlighting the similarities and differences in handling splices and quotes. ```scala s" Hello $name" s" Hello ${name}" '{ hello($name) } '{ hello(${name}) } ${ hello('name) } ${ hello('{name}) } ``` -------------------------------- ### Define Operators via Extension Methods in Scala Source: https://docs.scala-lang.org/scala3/reference/contextual/extension-methods.html Shows how to use extension method syntax to define custom operators or infix methods. Includes examples of standard and right-associative operators. ```scala extension (x: String) def < (y: String): Boolean = ... extension (x: Elem) def +: (xs: Seq[Elem]): Seq[Elem] = ... extension (x: Number) infix def min (y: Number): Number = ... "ab" < "c" 1 +: List(2, 3) x min 3 ``` -------------------------------- ### Leading infix operator indentation Source: https://docs.scala-lang.org/scala3/reference/other-new-features/indentation.html Example showing how indentation rules handle leading infix operators to ensure correct expression parsing. ```scala one + two.match case 1 => b case 2 => c + three ``` -------------------------------- ### Experimental Definitions in Scala 3: Signatures Scope Source: https://docs.scala-lang.org/scala3/reference/other-new-features/experimental-defs.html Illustrates that the signatures of experimental `def`, `val`, `var`, `given`, `type`, and constructors of `class` and `trait` are experimental scopes. Provides examples of correct and incorrect referencing within these scopes. ```scala import scala.annotation.experimental @experimental def x = 2 @experimental class A @experimental type X @experimental type Y = Int @experimental opaque type Z = Int def test1( p1: A, // error: class A is marked @experimental and therefore ... p2: List[A], // error: class A is marked @experimental and therefore ... p3: X, // error: type X is marked @experimental and therefore ... p4: Y, // error: type Y is marked @experimental and therefore ... p5: Z, // error: type Z is marked @experimental and therefore ... p6: Any = x // error: def x is marked @experimental and therefore ... ): A = ??? // error: class A is marked @experimental and therefore ... @experimental def test2( p1: A, p2: List[A], p3: X, p4: Y, p5: Z, p6: Any = x ): A = ??? class Test1( p1: A, // error p2: List[A], // error p3: X, // error p4: Y, // error p5: Z, // error p6: Any = x // error ) {} @experimental class Test2( p1: A, p2: List[A], p3: X, p4: Y, p5: Z, p6: Any = x ) {} trait Test1( p1: A, // error p2: List[A], // error p3: X, // error p4: Y, // error p5: Z, // error p6: Any = x // error ) {} @experimental trait Test2( p1: A, p2: List[A], p3: X, p4: Y, p5: Z, p6: Any = x ) {} ``` -------------------------------- ### Create Scala 3 Project with Staging Enabled (sbt) Source: https://docs.scala-lang.org/scala3/reference/metaprogramming/staging.html Command to create a new Scala 3 project pre-configured with staging support using the `sbt new` command and the `scala/scala3-staging.g8` template. This simplifies setting up a project for multi-stage programming experiments. ```bash sbt new scala/scala3-staging.g8 ``` -------------------------------- ### Scala Read-Only Access Example: `this` Reference Source: https://docs.scala-lang.org/scala3/reference/experimental/capture-checking/mutability.html Illustrates a read-only access within a Scala class `Ref`. The `get` method provides read-only access to the `current` variable, demonstrating a scenario where `this` is accessed in a read-only manner from a non-update method. ```scala class Ref[T] extends Mutable: var current: T def get: T = this.current // read-only access to `this` ``` -------------------------------- ### Compile and Run Scala Code with Staging (scalac/scala) Source: https://docs.scala-lang.org/scala3/reference/metaprogramming/staging.html Demonstrates how to compile and run Scala code directly using `scalac` and `scala` commands when staging is enabled. The `-with-compiler` flag is essential for both compilation and execution to support the staging features. ```bash scalac -with-compiler -d out Test.scala scala -with-compiler -classpath out Test ``` -------------------------------- ### Scala Read-Only Access Example: Normal Method Call Source: https://docs.scala-lang.org/scala3/reference/experimental/capture-checking/mutability.html Shows a read-only access to a reference `r` when calling its normal method `get`. This is allowed because the access is to a regular method, not an update method, making the context opportunistic for read-only declaration. ```scala val r: Ref[Int]^ = Ref(22) r.get // read-only access to `r` ``` -------------------------------- ### Scala 3.5+: Most General Given Selection for Ambiguous Matches Source: https://docs.scala-lang.org/scala3/reference/changed-features/implicit-resolution.html Starting from Scala 3.5, when comparing two givens that both match an expected type, the most general one is picked instead of the most specific one (as was the case in earlier Scala versions). Compiling with Scala 3.5-migration will warn about changes in preference. The example shows how `summon[A]` now resolves to `given_A`. ```scala class A class B extends A class C extends A given A = A() given B = B() given C = C() summon[A] // was ambiguous, will now return `given_A` ``` -------------------------------- ### Defining Capability Classes with SharedCapability in Scala Source: https://docs.scala-lang.org/scala3/reference/experimental/capture-checking/basics.html Demonstrates how to define capability classes like FileSystem and Logger by extending SharedCapability. It shows how capture sets are implicitly handled and how capabilities can be passed as implicit parameters, reducing wiring overhead. ```scala import caps.SharedCapability class FileSystem extends SharedCapability class Logger(using FileSystem): def log(s: String): Unit = ??? def test(using fs: FileSystem) = val l: Logger^{fs} = Logger() ... ``` -------------------------------- ### Invalid Export Clause Examples Source: https://docs.scala-lang.org/scala3/reference/other-new-features/export.html Examples of invalid export clauses demonstrating restrictions on renamings and hidden members. ```scala export {A as B, B} // error: B is hidden export {A as C, B as C} // error: duplicate renaming ``` -------------------------------- ### Defining a command-line program with @main Source: https://docs.scala-lang.org/scala3/reference/changed-features/main-functions.html Demonstrates how to use the @main annotation to create an executable method. It accepts typed parameters and supports repeated parameters for variable command-line arguments. ```scala @main def happyBirthday(age: Int, name: String, others: String*) = val suffix = age % 100 match case 11 | 12 | 13 => "th" case _ => age % 10 match case 1 => "st" case 2 => "nd" case 3 => "rd" case _ => "th" val bldr = new StringBuilder(s"Happy $age$suffix birthday, $name") for other <- others do bldr.append(" and ").append(other) bldr.toString ``` -------------------------------- ### Named Tuple Restriction Examples Source: https://docs.scala-lang.org/scala3/reference/other-new-features/named-tuples.html Examples of illegal operations involving Named Tuples, such as mixing named and unnamed elements or duplicate field names. ```scala // Error: Mixing named and unnamed val illFormed1 = ("Bob", age = 33) // Error: Duplicate names val illFormed2 = (name = "", age = 0, name = true) // Error: Matching regular tuple with named pattern (tuple: Tuple) match { case (age = x) => // error } ``` -------------------------------- ### Defining a main program with command line arguments in Scala 3 Source: https://docs.scala-lang.org/scala3/reference/dropped-features/delayed-init.html Shows the recommended approach for handling command-line arguments by defining an explicit main method within an object. ```scala object Hello: def main(args: Array[String]) = println(s"Hello, ${args(0)}") ``` -------------------------------- ### Indentation alignment error example Source: https://docs.scala-lang.org/scala3/reference/other-new-features/indentation.html Example of invalid indentation in Scala 3 that causes a compiler error due to misalignment of the 'else' block. ```scala if x < 0 then -x else // error: `else` does not align correctly x ``` -------------------------------- ### Scala Soft Union Type Inference Example Source: https://docs.scala-lang.org/scala3/reference/new-types/union-types-spec.html Shows an example of a 'soft' union type that arises from type inference in Scala, specifically from an `if-else` expression. ```scala val x = 1 val y = "abc" if cond then x else y ``` ```scala The type of this expression is the soft union type `Int | String`. ``` -------------------------------- ### Defining a main program using App in Scala 3 Source: https://docs.scala-lang.org/scala3/reference/dropped-features/delayed-init.html Demonstrates the usage of the App class for simple program initialization. Note that this approach is not recommended for performance-critical code or benchmarking due to JVM interpretation behavior. ```scala object HelloWorld extends App { println("Hello, world!") } ``` -------------------------------- ### Defining and Using Preview Features in Scala 3 Source: https://docs.scala-lang.org/scala3/reference/other-new-features/preview-defs.html Demonstrates how to define a function using the @preview annotation and how to enable preview mode using the 'using options' directive. It also shows how preview features can be wrapped for transitive use in non-preview scopes. ```scala //> using options -preview package scala.stdlib import scala.annotation.internal.preview @preview def previewFeature: Unit = () // Can be used in non-preview scope def usePreviewFeature = previewFeature ``` ```scala def usePreviewFeatureTransitively = scala.stdlib.usePreviewFeature def usePreviewFeatureDirectly = scala.stdlib.previewFeature // error - referring to preview definition outside preview scope ``` -------------------------------- ### Example of 'into' Type Constructor Usage Source: https://docs.scala-lang.org/scala3/reference/preview/into.html A practical example showing how 'into' allows an Array to be passed to a method expecting an IterableOnce without an explicit import. ```scala given Conversion[Array[Int], IterableOnce[Int]] = wrapIntArray val xs: List[Int] = List(1) val ys: Array[Int] = Array(2, 3) xs ++ ys ``` -------------------------------- ### Restricted Capability Example (Scala) Source: https://docs.scala-lang.org/scala3/reference/experimental/capture-checking/classifiers.html Illustrates how restricted capabilities work with concrete examples of capability classes. It shows the resulting capture set when capabilities unrelated to the classifier are dropped. ```scala class IO extends caps.SharedCapability class Async extends caps.Control def test(io: IO, async: Async, proc: () => Unit) = val r = Try: // code accessing `io`, `async`, and `proc` and returning an `Int`. val _: Try[Int]^{async, proc} = r ``` -------------------------------- ### Demonstrate subcapturing relations Source: https://docs.scala-lang.org/scala3/reference/experimental/capture-checking/basics.html Provides examples of how capture sets relate to one another, showing that the root capability {cap} covers all other sets and how local variables are widened during type checking. ```scala fs: FileSystem^ ct: CanThrow[Exception]^ l : Logger^{fs} // Subcapturing relations: // {l} <: {fs} <: {cap} // {fs} <: {fs, ct} <: {cap} // {ct} <: {fs, ct} <: {cap} ``` -------------------------------- ### Scala Union Type Join Example Source: https://docs.scala-lang.org/scala3/reference/new-types/union-types-spec.html Provides an example of calculating the join and visible join of a union type `A | B` in Scala, given specific trait and class definitions. ```scala trait C[+T] trait D trait E transparent trait X class A extends C[A], D, X class B extends C[B], D, E, X ``` ```scala The join of `A | B` is `C[A | B] & D & X` and the visible join of `A | B` is `C[A | B] & D`. ``` -------------------------------- ### Accessing TASTy Reflection in Macros Source: https://docs.scala-lang.org/scala3/reference/metaprogramming/reflection.html Demonstrates how to set up a macro implementation using the Quotes context to access reflection capabilities. It shows the basic structure for defining an inline macro and its corresponding implementation. ```scala import scala.quoted.* inline def natConst(inline x: Int): Int = ${natConstImpl('{x})} def natConstImpl(x: Expr[Int])(using Quotes): Expr[Int] = import quotes.reflect.* ... ``` -------------------------------- ### Scala 3 Named Tuple Source Incompatibility Examples Source: https://docs.scala-lang.org/scala3/reference/other-new-features/named-tuples.html Examples demonstrating how previous assignment syntax and infix operator calls may be reinterpreted as named tuples in Scala 3. ```Scala var age: Int (age = 1) class C: infix def f(age: Int) val c: C c f (age = 1) ``` -------------------------------- ### Using Scala 3 Compiler Plugins with scalac Source: https://docs.scala-lang.org/scala3/reference/changed-features/compiler-plugins.html Demonstrates how to enable Scala 3 compiler plugins using the `-Xplugin:` option with `scalac`. This method is used for both standard and research plugins. ```bash scalac -Xplugin:pluginA.jar -Xplugin:pluginB.jar Test.scala ``` -------------------------------- ### Scala 3 Typeable - Usage Example Source: https://docs.scala-lang.org/scala3/reference/other-new-features/type-test.html Provides an example of using the `Typeable` type alias as a context bound in a Scala 3 function. This demonstrates how `Typeable` simplifies type testing within functions. ```scala def f[T: Typeable]: Boolean = "abc" match case x: T => true case _ => false f[String] // true f[Int] // false ``` -------------------------------- ### Instantiate and Run TASTy Inspector in Scala Source: https://docs.scala-lang.org/scala3/reference/metaprogramming/tasty-inspect.html This Scala code demonstrates how to instantiate the `TastyInspector` and run it with a list of TASTy files and a custom inspector. It shows the basic setup for inspecting TASTy files programmatically. ```scala object Test: def main(args: Array[String]): Unit = val tastyFiles = List("foo/Bar.tasty") TastyInspector.inspectTastyFiles(tastyFiles)(new MyInspector) ``` -------------------------------- ### Scala 3 Postconditions Manual Expansion Source: https://docs.scala-lang.org/scala3/reference/contextual/context-functions.html Illustrates the manual expansion of the 'ensuring' method call, demonstrating how the assertion is checked and the original value is returned. This shows the zero-overhead nature of the abstraction. ```scala val s = val result = List(1, 2, 3).sum assert(result == 6) result ``` -------------------------------- ### Examples of `Box` Comparisons with Multiversal Equality in Scala Source: https://docs.scala-lang.org/scala3/reference/contextual/multiversal-equality.html Provides examples of comparing instances of a generic `Box` class, demonstrating successful comparisons when `CanEqual` instances exist for the contained types and errors otherwise. ```scala new Box(1) == new Box(1L) // ok since there is an instance for `CanEqual[Int, Long]` new Box(1) == new Box("a") // error: can't compare new Box(1) == 1 // error: can't compare ``` -------------------------------- ### Scala 3 Generalized Method Syntax Example Source: https://docs.scala-lang.org/scala3/reference/other-new-features/generalized-method-syntax.html Demonstrates the enhanced method syntax in Scala 3, permitting any number of type clauses at various positions, with a note on discouraging implicit clauses in favor of using clauses. ```scala def foo[T, U](x: T)(y: U)[V](z: V, s: String)(using Ord[Int])[A](a: Array[A])(implicit List[U]) ``` -------------------------------- ### Scala 2 Method Syntax Example Source: https://docs.scala-lang.org/scala3/reference/other-new-features/generalized-method-syntax.html Illustrates the traditional method syntax in Scala 2, which allowed only zero or one type parameter clause followed by term and optional implicit clauses. ```scala def foo[T, U](x: T)(y: U)(z: Int, s: String)(a: Array[T])(implicit ordInt: Ord[Int], l: List[U]) ``` -------------------------------- ### Legacy Scala 2 App object pattern Source: https://docs.scala-lang.org/scala3/reference/changed-features/main-functions.html Shows the deprecated Scala 2 approach for creating main programs using the App trait, provided for cross-version context. ```scala object happyBirthday extends App: // needs by-hand parsing of arguments vector ... ``` -------------------------------- ### Scala Read-Only Access Example: Path Reference Source: https://docs.scala-lang.org/scala3/reference/experimental/capture-checking/mutability.html Shows read-only access to a reference `r` through a path. This example highlights how a read-only capture set (`^{cap.rd}`) on the reference itself or a prefix allows for read-only access to its members. ```scala val r: Ref[Int]^{cap.rd} = new Ref[T](22) def get = r.get // read-only access to `r` ``` -------------------------------- ### Scala 3 Context Function Application Source: https://docs.scala-lang.org/scala3/reference/contextual/context-functions.html Demonstrates how to define and apply functions with context parameters using the '?=>' syntax. It shows both explicit and inferred argument passing for context parameters. ```scala given ec: ExecutionContext = ... def f(x: Int): ExecutionContext ?=> Int = ... // could be written as follows with the type alias from above // def f(x: Int): Executable[Int] = ... f(2)(using ec) // explicit argument f(2) // argument is inferred ``` -------------------------------- ### Opaque Type Aliases with Type Parameters in Scala Source: https://docs.scala-lang.org/scala3/reference/other-new-features/opaques-details.html Provides examples of well-formed opaque type aliases that include type parameters in Scala. It contrasts these with malformed examples that do not adhere to the allowed parameter list structures. ```scala opaque type F[T] = (T, T) opaque type G = [T] =>> List[T] ``` ```scala opaque type BadF[T] = [U] =>> (T, U) opaque type BadG = [T] =>> [U] =>> (T, U) ``` -------------------------------- ### Scala 3 Dependent Function Type Examples Source: https://docs.scala-lang.org/scala3/reference/new-types/dependent-function-types-spec.html Demonstrates the usage of dependent function types (DF and IDF) and their application in Scala 3. This example defines a trait C and shows how to instantiate and use dependent functions. ```scala trait C { type M; val m: M } type DF = (x: C) => x.M type IDF = (x: C) ?=> x.M @main def test = val c = new C { type M = Int; val m = 3 } val depfun: DF = (x: C) => x.m val t = depfun(c) println(s"t=$t") // prints "t=3" val idepfun: IDF = summon[C].m val u = idepfun(using c) println(s"u=$u") // prints "u=3" ``` -------------------------------- ### Scala 3 Named Tuples: Initialization and Function Calls Source: https://docs.scala-lang.org/scala3/reference/other-new-features/named-tuples.html Illustrates alternative ways to initialize named tuples, including using regular tuples and named arguments in function calls. It highlights the subtyping relationship between regular and named tuples. ```scala val Laura: Person = ("Laura", 25) def register(person: Person) = ... register(person = ("Silvain", 16)) register(("Silvain", 16)) ``` -------------------------------- ### Scala 3 Given Instance Syntax Source: https://docs.scala-lang.org/scala3/reference/contextual/previous-givens.html Provides the formal grammar for defining given instances in Scala 3. It covers structural instances, alias instances, and abstract instances, along with their signatures. ```scala TmplDef ::= ... | 'given' GivenDef GivenDef ::= [GivenSig] StructuralInstance | [GivenSig] AnnotType ‘=’ Expr | [GivenSig] AnnotType GivenSig ::= [id] [DefTypeParamClause] {UsingParamClause} ':' StructuralInstance ::= ConstrApp {'with' ConstrApp} [‘with’ TemplateBody] ``` -------------------------------- ### Java List Get Method with Unsafe Nulls in Scala Source: https://docs.scala-lang.org/scala3/reference/experimental/explicit-nulls.html Highlights a limitation of `unsafeNulls` when interacting with Java methods that return potentially null values. The `get` method on `java.util.List` returns `T | Null`, requiring an explicit `.nn` to cast to `T`. ```scala def head[T](xs: java.util.List[T]): T = xs.get(0) // error // To fix: def head[T](xs: java.util.List[T]): T = xs.get(0).nn ``` -------------------------------- ### Scala: Reimplementing fromProduct with Pattern Matching Source: https://docs.scala-lang.org/scala3/reference/experimental/unrolled-defs.html Demonstrates how the `fromProduct` method in Scala 3 is reimplemented using pattern matching on `productArity` to preserve semantic compatibility. It shows the generation of cases for a case class primary constructor and a default wildcard case. ```Scala case class C(ps0...) // ps0 has z parameters object C: def fromProduct(p: Product): C = p.productArity match case ... => ... case n => new C(...p.productElement(n - 1), ds...) case _ => new C(...p.productElement(z - 1)) ``` -------------------------------- ### Mutable Reference Cell Example (Scala) Source: https://docs.scala-lang.org/scala3/reference/experimental/capture-checking/mutability.html Demonstrates a mutable reference cell using the `caps.Mutable` trait. This allows for both reading and writing to the cell's field. The example shows how function types reflect the read/write capabilities of the enclosed state. ```Scala import caps.Mutable class Ref[T](init: T) extends Mutable: var fld: T val r: Ref[Int]^ = Ref(22) // Function that writes to r.fld val writeFunc: () ->{r} Unit = () => r.fld += 1 // Function that reads r.fld val readFunc: () ->{r.rd} Int = () => r.fld ``` -------------------------------- ### Define and Use Scala 3 Macros across Compilation Stages Source: https://docs.scala-lang.org/scala3/reference/metaprogramming/macros.html Demonstrates the separation of macro definitions and their usage across different source files. The example shows a macro implementation in a library and its subsequent invocation in an application. ```scala // Macro.scala def powerCode(x: Expr[Double], n: Expr[Int])(using Quotes): Expr[Double] = ... inline def powerMacro(x: Double, inline n: Int): Double = ${ powerCode('x, 'n) } ``` ```scala // Lib.scala (depends on Macro.scala) def power2(x: Double) = ${ powerCode('x, '{2}) } // inlined from a call to: powerMacro(x, 2) ``` ```scala // App.scala (depends on Lib.scala) @main def app() = power2(3.14) ``` -------------------------------- ### Define and use context parameters with using clauses Source: https://docs.scala-lang.org/scala3/reference/contextual/using-clauses.html Demonstrates how to define a function with a context parameter using the 'using' keyword and how to call it with or without explicit arguments. ```scala def max[T](x: T, y: T)(using ord: Ord[T]): T = if ord.compare(x, y) < 0 then y else x // Usage max(2, 3)(using intOrd) max(2, 3) max(List(1, 2, 3), Nil) ``` -------------------------------- ### Obtaining Macro Expansion Position Information Source: https://docs.scala-lang.org/scala3/reference/metaprogramming/reflection.html Shows how to retrieve detailed position information about a macro's expansion site using `Position.ofMacroExpansion`. This includes source file path, start/end positions, line/column numbers, and the source code at the expansion point. It handles potential virtual file systems. ```scala def macroImpl()(quotes: Quotes): Expr[Unit] = import quotes.reflect.* val pos = Position.ofMacroExpansion val jpath = pos.sourceFile.getJPath.getOrElse(report.errorAndAbort("virtual file not supported", pos)) val path = pos.sourceFile.path // fallback for a virtual file val start = pos.start val end = pos.end val startLine = pos.startLine val endLine = pos.endLine val startColumn = pos.startColumn val endColumn = pos.endColumn val sourceCode = pos.sourceCode ... ``` -------------------------------- ### Scala 3: `into` Modifier Subclassing Limitation Example Source: https://docs.scala-lang.org/scala3/reference/preview/into.html Illustrates a limitation in Scala 3 where subclasses of `into` declared types are not considered valid conversion target types. This example shows that direct extension does not inherit the `into` property for implicit conversion purposes. ```scala into trait T class C(x: Int) extends T given Conversion[Int, C] = C(_) def f(x: T) = () def g(x: C) = () f(1) // ok g(1) // error ``` -------------------------------- ### Instantiate classes without 'new' in Scala 3 Source: https://docs.scala-lang.org/scala3/reference/other-new-features/creator-applications.html Demonstrates how Scala 3 allows class instantiation using function application syntax by generating constructor proxies. This eliminates the need for the 'new' keyword for concrete classes. ```scala class StringBuilder(s: String): def this() = this("") StringBuilder("abc") // old: new StringBuilder("abc") StringBuilder() // old: new StringBuilder() ``` -------------------------------- ### Scala 3: Missing brace error example with indentation Source: https://docs.scala-lang.org/scala3/reference/other-new-features/indentation.html Illustrates a common error in Scala 3 where a missing opening brace leads to incorrect indentation. This example shows how the compiler flags this issue when significant indentation is turned off, preventing potential bugs. ```scala if (x < 0) println(1) println(2) // error: missing `{` ``` -------------------------------- ### Applied Constructor Types Example (Scala) Source: https://docs.scala-lang.org/scala3/reference/experimental/modularity.html Provides an example of applied constructor types with a class having multiple 'tracked' parameters. It demonstrates how a type like 'Person("Kasia", 27)' translates to a refined type 'Person { val name: "Kasia"; val age: 27 }'. ```scala class Person(tracked val name: String, tracked val age: Int) // Type Person("Kasia", 27) will be translated to Person { val name: "Kasia"; val age: 27 } ``` -------------------------------- ### Defining and using macros Source: https://docs.scala-lang.org/scala3/reference/metaprogramming/macros.html Shows the implementation of top-level splices for macros and the use of inline methods to provide an ergonomic interface for end-users, hiding metaprogramming details. ```scala def power2(x: Double): Double = ${ unrolledPowerCode('x, 2) } // x * x ``` ```scala // inline macro definition inline def powerMacro(x: Double, inline n: Int): Double = ${ powerCode('x, 'n) } // user code def power2(x: Double): Double = powerMacro(x, 2) // x * x ``` -------------------------------- ### Implement auto-boxing conversion Source: https://docs.scala-lang.org/scala3/reference/contextual/conversions.html Example of mapping primitive types to object wrappers using the Conversion class. ```scala given int2Integer: Conversion[Int, java.lang.Integer] = java.lang.Integer.valueOf(_) ``` -------------------------------- ### Invoking Escaped Capability Source: https://docs.scala-lang.org/scala3/reference/experimental/canthrow.html Example of calling a function that returns a closure containing an escaped capability, resulting in a runtime exception. ```scala val g = escaped(1, 2, 1000000000) g() ``` -------------------------------- ### Scala 3 TypeTest - Manual Instance Creation Source: https://docs.scala-lang.org/scala3/reference/other-new-features/type-test.html Demonstrates how to manually create a `TypeTest` instance at the call site for runtime class tests. This is useful when the compiler cannot infer the `TypeTest` automatically. ```scala val tt: TypeTest[Any, String] = new TypeTest[Any, String]: def unapply(s: Any): Option[s.type & String] = s match case q: (s.type & String) => Some(q) case _ => None f[AnyRef, String]("acb")(using tt) ```