Relative scoping for hierarchical ADT arguments

.() looks weird for syntactic reasons, e.g. because Map.() is not allowed, but eliding the Map name on the right is not so bad:

val loop3: Map[Int, T] = (0 -> 1, 1 -> 2, 2 -> 0)

Unusual? Maybe, but these just landed in C# 12 as Sequence Expressions a few months ago:

// Create an array:
int[] a = [1, 2, 3, 4, 5, 6, 7, 8];

// Create a list:
List<string> b = ["one", "two", "three"];

// Create a span
Span<char> c  = ['a', 'b', 'c', 'd', 'e', 'f', 'h', 'i'];

// Create a jagged 2D array:
int[][] twoD = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];

Sequence expressions would also be directionally in line with other experimental Scala 3 features such as Numeric Literals, which also overload the literal syntax to allow various types to be constructed from the same numeric literal syntax via target typing

This is maybe separate/orthogonal to the original proposal, but IMO the current level of “boilerplate” in Scala is “fine”, but nowhere near ideal. Apart from dynamic languages like Python or Javascript that have concise untyped collection literals, we see languages like C# moving towards that level of conciseness while fully statically-typed by making use of target-typing. Given the renewed vigor with which Java has been evolving, I wouldn’t be surprised at all if Java followed suit in a year or two


Circling back to the original proposal, Swift’s usage of leading .foo to refer to pkg.prefix.TargetType.foo is a small but significant improvement over Scala, which traditionally has 3 bad options:

  1. Verbosely use fully-qualified names to refer to things
  2. Verbosely importing things and polluting your local namespace
  3. Avoiding hierarchical namespaces, and putting everything in one huge flat namespace you import stuff.*

The leading .foo solves this entirely: it allows you to be totally concise, keep your local scope clean, while still organizing your code neatly into hierarchical namespaces. And the target-type-driven desugaring is simple, understandable, and unambiguous.

It’s definitely an unusual syntax, and superficially less elegant than un-prefixed foo, but the . has so many upsides in backwards-compat, simplicity of spec, and un-ambiguousness (for humans) that IMO it’s worth it

3 Likes