Skip to content

SIP-80: Companion Scope Inference - #134

Open
soronpo wants to merge 5 commits into
scala:mainfrom
soronpo:claude/plan-adt-scoping-sip-AMlqd
Open

soronpo wants to merge 5 commits into
scala:mainfrom
soronpo:claude/plan-adt-scoping-sip-AMlqd

Conversation

@soronpo

@soronpo soronpo commented May 6, 2026

Copy link
Copy Markdown
Contributor

No description provided.

@lihaoyi

lihaoyi commented May 6, 2026 •

Copy link
Copy Markdown
Contributor

Looks amazing in general.


The same restriction applies to any polymorphic call where `.X` would be the sole source of information about a type parameter: the inference machinery sees the relative-scope position as having an unknown expected type and stops. Lifting this is future work and would require relative-scope resolution to *contribute* candidate types back to inference rather than just consume an established expected type. It is the same underlying entanglement that the same-arity overloading restriction sidesteps.

#### Infix applications

@lihaoyi lihaoyi May 6, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's probably worth mentioning that this is the same rule applied when resolving _ to target-type lambdas: they resolve to the nearest enclosing parentheses, and so added or removing parentheses can change the semantics of code even if it doesn't affect the associativity or order of operations

// The two `_`s are not wrapped in parentheses, and so both are scoped to the enclosing `=`
val x: (Int, Int) => Int = Seq(1,2,3) map "" + _ apply _ 
// The first `_` is wrapped in parentheses, and so is scoped to the parentheses
val x: Int => String = Seq(1,2,3) map ("" + _) apply _

While this is a bit odd, it seems to work out reasonably well in practice, and we can use the same rule for target-typed companion scoping


### Specification

#### Triggering positions

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should try to make sure this list lines up with how _ lambdas are resolved to their target types, since it's semantically very similar and we should try and avoid unnecessary divergance

@soronpo soronpo May 6, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is lambda supported in if expressions?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems the if/else acts as a boundary for _ binding

Welcome to the Ammonite Repl 3.0.2 (Scala 2.13.16 Java 21.0.9)
@ val f: Int => Int = if (true) _ + 1 else _ + 2 
f: Int => Int = ammonite.$sess.cmd0$$$Lambda/0x000000b0025d0000@7516e4e5

soronpo pushed a commit to soronpo/scala-sips that referenced this pull request May 6, 2026
Refines the overload-resolution rule in response to PR review:
when default arguments make multiple overloads viable for the same
call arity, .X resolves successfully provided the candidates agree
on the parameter type at the .X position. This is the same flavour
of rule that already governs target-typed `_` in Scala.

Use site is still an error only when candidates genuinely differ at
the .X position. Worked examples cover four cases:
- different declared arities, single match (existing)
- default args making multiple arities viable, shared param type
- same-arity, shared param type at .X position
- same-arity, differing param types (error, with workarounds)

Per scala#134 (review).

https://claude.ai/code/session_017ZixGxpc2ShVSUJnU6wtDt
soronpo pushed a commit to soronpo/scala-sips that referenced this pull request May 6, 2026
The original title implied a new scoping rule and limited the
feature to hierarchical ADTs. The new title describes both the
mechanism (target-typed) and where the lookup happens (companion),
and reflects that the feature applies to any companion member, not
just enum/sealed ADT cases.

Per scala#134 (review).

https://claude.ai/code/session_017ZixGxpc2ShVSUJnU6wtDt
@soronpo soronpo changed the title SIP-80: Relative Scoping for Hierarchical ADT Arguments SIP-80: Target-Typed Companion Shorthand May 6, 2026
soronpo pushed a commit to soronpo/scala3 that referenced this pull request May 6, 2026
Adds an experimental `experimental.targetTypedCompanionShorthand` feature
that lets a leading `.` followed by an identifier in target-typed positions
desugar to `T.X`, where `T` is the inferred expected type. For example,
with `final case class Shape(geometry: Geometry, color: Color)`,
`Shape(.Circle, .Red)` resolves to `Shape(Geometry.Circle, Color.Red)`.

Implementation:
- `untpd.RelativeSelect(name)` is a new untyped tree produced by the parser
  when DOT is followed by IDENTIFIER at the start of `simpleExpr` or
  `simplePattern`, gated on `Feature.featureEnabled(targetTypedCompanionShorthand)`.
- `Typer.typedRelativeSelect` peels prototype layers (SelectionProto /
  IgnoredProto / FunProto / PolyProto), unwraps `T | Null` and `Null | T`,
  and reads upper bounds of uninstantiated TypeVars (so `Some(.Red)` with
  target `Option[Color]` resolves via `A <: Color`). It looks up the alias's
  companion via `prefix.member`, so opaque type aliases, transparent type
  aliases, `import`-introduced and `export`-introduced types resolve against
  their own companion rather than the underlying class's. Re-enters
  `typedSelect` with `Select(companionRef, name)` and the original `pt`,
  reusing overload selection, implicit conversions via `adapt`, and
  pattern-mode handling without bespoke logic.
- `Applications.pretypeArgs` recognises `untpd.RelativeSelect` arguments:
  if all surviving overload candidates share the same formal at the arg
  position, it pre-types `.X` against that formal. This handles the common
  binary-compatibility evolution pattern of overloads-with-default-args
  (see SIP review comment
  scala/improvement-proposals#134 (comment)),
  e.g. `def bar(a: Animal): Unit` together with
  `def bar(a: Animal, b: Animal = null): Unit` accepts `bar(.Cat)`.

Compatibility: the new syntax only fires at fresh-expression positions
where leading `.` was previously a parse error. Method-chain continuation
(`expr\n.foo`) is unaffected because it's handled by `simpleExprRest`,
not `simpleExpr`. The desugaring is removed at typer time, so there are
no TASTy or binary changes.

Tests cover positive cases (basic, hierarchical chain, application form,
patterns including `|` alternatives, named arguments, `using` clauses,
opaque types, enum cases, implicit conversions, type aliases, `import`
and `export`-introduced types, varargs, overload-by-arity, default-arg
overloads, `T | Null` peeling, type-parameter inference from result type
including `Some(.Red): Option[Color]`, `Right(.Red): Either[L, Color]`,
run test) and negative cases (missing language import, missing companion
member, type without companion, undetermined expected type, ambiguous
same-arity overload, infix-operator RHS).

Documentation:
- Reference page under `docs/_docs/reference/experimental/`
  (`target-typed-companion-shorthand.md`) covering the feature, examples,
  errors, and the documented v1 limitations (infix RHS, same-arity
  overloads with disjoint formals, bare `.@@` cursor) with workarounds.
- Spec grammar updates in `docs/_spec/06-expressions.md` and
  `docs/_spec/08-pattern-matching.md` adding the new SimpleExpr1 /
  SimplePattern productions.

https://claude.ai/code/session_015qU7ZLw5rKPF6gXczLyuhq
@odersky

odersky commented May 6, 2026 •

Copy link
Copy Markdown
Contributor

I am still totally opposed. This looks like non-sensical line noise to me. I tried hard to make line noise code rare in Scala 3, but this would bring it back. If we want scope injection, let's restrict it to enums, and forget about the leading ..

@soronpo

soronpo commented May 6, 2026

Copy link
Copy Markdown
Contributor Author

I am still totally opposed. This looks like non-sensical line noise to me. I tired hard to make line noise code rare in Scala 3, but this would bring it back. If we want scope injection, let's restrict it to enums, and forget about the leading ..

I'll be submitting it to the committee as-is. If it's rejected, then fine. Where you see noise, I see clarity. It's subjective. As discussed before and also within this SIP, this syntax also exists in other languages.

@bjornregnell

Copy link
Copy Markdown

This looks like non-sensical line noise to me

I agree @odersky that it looks alien at a first glance, but there are elaborate arguments in the proposal for this syntax. Perhaps it is possible to get used to the leading dot so that it makes more sense after a while? But it is for sure increasing the opportunity of "symbol salad" in the name of terseness, rather than prioritizing making things explicit for a first reader.

I write mostly flat enums, but I can imagine that there are use cases in DSL design. And I guess @soronpo have the greater scope of not just enums, due to DSL usage ergonomics?

The question is if this potentially cryptic syntax is worth the ergonomics.

@bjornregnell

Copy link
Copy Markdown

@soronpo What do you think about accepting only target typing for enums and no leading dot?

@lihaoyi

lihaoyi commented May 6, 2026 •

Copy link
Copy Markdown
Contributor

IMO restricting it to enums kills much of the usefulness - factory methods, adoption by existing libraries, etc. - and no-leading-dot replaces a trivial un-ambiguous syntactic marker with much more complicated scope resolution changes that result in actual ambiguity that will need to be dis-ambiguated with complicated rules

@soronpo

soronpo commented May 6, 2026

Copy link
Copy Markdown
Contributor Author

@soronpo What do you think about accepting only target typing for enums and no leading dot?

I'm against it. I think it's too surprising, and it doesn't really solve all my use-cases. A leading dot also helps with triggering completions only when I want them and limits their scope. Without the leading dot names can come from everywhere.

I am willing to limit the proposal to accept only values/objects (no method application or constructors) if it helps to reduce potential abuse.

Other than that, somone else can feel free to introduce their own proposal with the restrictions Odersky proposed.

@lihaoyi

lihaoyi commented May 6, 2026 •

Copy link
Copy Markdown
Contributor

As discussed in the original contributors thread, factory methods are a huge use case, for Scala libraries like Laminar which define parametrized properties, and for the same feature in other languages like SwiftUI which do the same. Parametrized constructors and factories are extremely common, and restricting it to enums would make enums privileged that would distort the design of libraries where enums may not always be the right answer

@spamegg1

spamegg1 commented May 6, 2026

Copy link
Copy Markdown

Whether restricted to enums or not, how would it play with Multi-level enums, depending on which gets accepted / implemented first? Should the SIP mention this? (maybe not)

@soronpo

soronpo commented May 6, 2026

Copy link
Copy Markdown
Contributor Author

Whether restricted to enums or not, how would it play with Multi-level enums, depending on which gets accepted / implemented first? Should the SIP mention this? (maybe not)

It might be worth mentioning. I'll add it as motivation. There is no specific order between the two. They mainly relate in the likelihood of them being rejected 😅 .

@lihaoyi

lihaoyi commented May 6, 2026 •

Copy link
Copy Markdown
Contributor

One thing worth mentioning is the dot-prefixed syntax while not quite standard does seem reasonably widely adopted, and seems to be the standard for any other language discussing any similar feature. We don't see any languages adopting or proposing alternate delimiters like .. or # or whatever, they all use .foo

While 10 years ago in 2016 I would agree that the dot-prefixed .foo syntax is kind of weird, in 2026 it does seem like the dot-prefixed syntax is emerging as a de-facto standard among programming languages for precisely this semantics, and looking forward I expect in 2036 we'd be seeing more of the dot-prefixed syntax as a convention throughout the programming language landscape

@soronpo maybe this should be included in the proposal as prior art?

Swift

view.backgroundColor = .systemBackground
let publisher = URLSession.shared.dataTaskPublisher(for: .swiftBySundell)

let x: SomeClass = .shared.a.f()
let y: SomeClass? = .shared
let z: SomeClass = .sharedSubclass

enum NetworkResult {
    case success(data: Data)
    case failure(error: Error)
    case pending
}

switch result {
case .success(let data):
    handle(data)
case .failure(let error):
    log(error)
case .pending:
    break
}

if case .success(let data) = result {
    handle(data)
}

for case .success(let data) in results {
    handle(data)
}

Zig

const dir: Direction = .north;
var gpa: std.heap.GeneralPurposeAllocator(.{}) = .init;

const color1: Color = .auto;
const color2 = Color.auto;
try expectEqual(color1, color2);

const color = Color.on;
const result = switch (color) {
    .auto => false,
    .on => true,
    .off => false,
};

Dart

enum Status { none, running, stopped, paused }

class Point {
  final double x, y;
  const Point(this.x, this.y);
  const Point.origin() : x = 0.0, y = 0.0;
}

// Use dot shorthand syntax for enum value:
const Status defaultStatus = .running; // Instead of Status.running

// Use dot shorthand syntax to invoke a const named constructor:
const Point myOrigin = .origin(); // Instead of Point.origin()

// Use dot shorthand syntax in a const collection literal:
const List<Point> keyPoints = [.origin(), .new(1.0, 1.0)];
// Instead of [Point.origin(), Point(1.0, 1.0)]

enum LogLevel { debug, info, warning, error }

/// Returns the color code to use for the specified log [level].
String colorCode(LogLevel level) {
  // Use dot shorthand syntax for enum values in switch cases:
  return switch (level) {
    .debug => 'gray', // Instead of LogLevel.debug
    .info => 'blue', // Instead of LogLevel.info
    .warning => 'orange', // Instead of LogLevel.warning
    .error => 'red', // Instead of LogLevel.error
  };
}

Lean

inductive Bar where
  | foo

def x : Bar := .foo

CSharp (Proposed)

type.GetMethod("Name", .Public | .Instance | .DeclaredOnly); // BindingFlags.Public | ...

control.ForeColor = .Red;          // Color.Red
entity.InvoiceDate = .Today;       // DateTime.Today
ReadJsonDocument(.Parse(stream));  // JsonDocument.Parse

// Production (static members on Option<int>)
Option<int> option = condition ? .None : .Some(42);

// Production (nested derived types)
CustomResult result = condition ? new .Success(42) : new .Error("message");

// Consumption (nested derived types)
return result switch
{
    .Success(var val) => val,
    .Error => defaultVal,
};

Rust (Proposed)

fn get_default_status() -> Status {
    .Pending(0.0)
}
update_status(.Pending(0.5));
update_status(.Complete { data: vec![1, 2, 3] });
update_status(.Failed);

match status {
    .Pending(progress) => ...,
    .Complete { data } => ...,
    .Failed => ...,
}

@soronpo

soronpo commented May 6, 2026

Copy link
Copy Markdown
Contributor Author

@soronpo maybe this should be included in the proposal as prior art?

Yes, will do, thanks!

@odersky

odersky commented May 6, 2026 •

Copy link
Copy Markdown
Contributor

None of the mentioned languages strikes me as particularly legible. We should do better than that. The main issue is that this introduces obscure syntax (yes, I insist that's what it is!) on the application side. One more inconsistency how a library can be used. It feels like infix all over again. That also had great use cases, but overall the heterogeneity of application styles was a price too high to pay.

So whatever we do, we should avoid creating one more way to shorten code for library users if the library designer has not opted into it. If all examples of a library's usage have fully qualified names, I do not want some "smart" user to use prefix . instead since it's shorter.

Here are some options I find acceptable:

  1. Do nothing. It's a minor inconvenience, and the downside of misuse of the new feature is much bigger than that.
  2. Restrict to enums and avoid the leading .. Enums is where the main problem arises since to a casual reader it is indeed not clear whether enum cases should be scoped in the companion object or next to it. So we can address that confusion by allowing both qualified and unqualified access.
  3. Restrict to enums and factory methods that are specially marked. (Maybe use export as a modifier?). This keeps the spirit that it's the library author who has to opt into the feature.

@odersky

odersky commented May 6, 2026 •

Copy link
Copy Markdown
Contributor

Allowing different styles on the application side is also bad for agent-generated code. Sure you can have coding style guidelines, like "never use refix dot" or "always use it", but I can't have a style that says: Avoid qualified names if the library author has provided for it.

@kyouko-taiga

Copy link
Copy Markdown
Contributor

Please clarify

import some.lib.*

object Some:
  enum Enum:
    case Foo

def f(x: Some.Enum): Int = 0

f(Foo)

Assuming some.lib defines Foo, now I technically have two Foos in my scope when I resolve the argument passed to f. Which one do I want? Well, it may seem obvious that I want Some.Enum.Foo here but the trick doesn't work because some.lib.Foo resolves first.

Now let's compare with that:

// ...
import Some.Enum.*
f(Foo)

That doesn't work either. At least I'm being told Foo is ambiguous but the essential issue remains: in this particular position of the tree, my namespace effectively contains two Foos and there is no concise way to select the one I want without explicit qualification, which I consider needless noise.

A leading sigil solves this issue. 🤷‍♀️

@arturopala

Copy link
Copy Markdown

in this particular position of the tree, my namespace effectively contains two Foos and there is no concise way to select the one I want

The target type of x is known, and there is only one Foo fitting in. No ambiguity.

@soronpo

soronpo commented May 13, 2026

Copy link
Copy Markdown
Contributor Author

A leading sigil solves this issue. 🤷‍♀️

Still, this proposal significantly diminishes the need to import or use full descriptor for companion terms. Only in the event of name shadowing you have to go back to the "workarounds" we have today. I'm in the sigil side of the isle, but I'm also realistic. I was convinced that we're better off with this proposal that might get accepted than one of the previous one who most likely would have not. Take what you can get...

@mberndt123

Copy link
Copy Markdown
Contributor

That doesn't work either. At least I'm being told Foo is ambiguous but the essential issue remains: in this particular position of the tree, my namespace effectively contains two Foos and there is no concise way to select the one I want without explicit qualification, which I consider needless noise.

I think this can be solved with what I proposed elsewhere in the thread: overload resolution based on the expected type. But that's probably something that should be done in a separate SIP.

The much more significant advantage of a sigil (or # as a placeholder, similar to the _ lambda placeholder) is that it can be used for factory methods, especially apply.

@kyouko-taiga

kyouko-taiga commented May 13, 2026 •

Copy link
Copy Markdown
Contributor

The target type of x is known, and there is only one Foo fitting in. No ambiguity.

Sadly no. IIUC the trick kicks in when name resolution fails to find a symbol. It won't fail in that way in the first example because the system will simply resolve the wrong Foo. It won't fail in that way in the second example because it will simply be ambiguous. @mberndt123 's suggestion would indeed fix the issue, but only at the cost of even more complexity if you ask me. And we haven't even started thinking about interactions with contextual abstractions.

Anyway, that's not really the point I was making and I'm not really interested in trying to find more tweaks to the rule. The two main objections I stated are:

  • The proposed solution relies on a hack that I believe will be the source of a lot of confusion, especially if we add more ways to trigger some special lookup later on. This concern can be empirically justified (at least in part) by the countless blog posts there exist about argument dependent lookup and SFINAE in C++.
  • The proposed feature is not easily discoverable.

I believe those objections are not subjective. There are many other objective arguments in favor of a sigil I could make but others have probably made them already.

There's no point debating everyone's personal taste and IMO that is the only actual obstacle standing in front of adopting a leading sigil. Taste is important, though, and I understand that it should have weight on the balance. I am of course disappointed that others don't share mine but it is what it is. That being said, I think the proposed compromise is harmful to the legibility of Scala while not covering valid use cases. I would prefer the status quo.

@odersky

odersky commented May 13, 2026

Copy link
Copy Markdown
Contributor

I am not really concerned about the scope confusion aspect. Scope rules are already quite complex in Scala. Not many people can immediately recall the relative precedences of declared, imported, inherited identifiers depending on nesting level. It's usually not a problem in practice, because people learn to not over-use the same name for different things.

So we add one more category where we resolve according to expected type. The relative precedence is that it comes last, which matches intuitions formed from implicit resolution. There we also try to find a given in scope (or imported, or inherited) and only if that fails we look at the expected type.

So, yes, having a sigil would make this one thing more explicit. But before we insist on that, we should really go back and force you to write this.foo instead of inherited foo because that's also confusing, right? What I am trying to say is: it's too late to worry about "namespace pollution". That boat as sailed, and I don't see many people having problems with it.

@soronpo

soronpo commented May 13, 2026 •

Copy link
Copy Markdown
Contributor Author

Thank you everyone for your contribution to the thread!!!

You have until the end of week to continue discussion here, but after that I will lock the discussion until the SIP is rewritten and the official reviewers get assigned to it.

@mberndt123

Copy link
Copy Markdown
Contributor

It would be nice to have an idea of how much code would break if we, say, put enum cases at the same precedence level as imported identifiers. Maybe we can create a prototype implementation where that is done and test it with the community build? Because I tend to think that actual ambiguities would be rare (and easily worked around), while the visual noise of sigils would be all over the place.

Another idea would be to introduce expected-type-based overload resolution first (so importing enum cases becomes less problematic), and only then add more name lookup rules.

@mberndt123

mberndt123 commented May 14, 2026 •

Copy link
Copy Markdown
Contributor

I find this wording a bit vague:

We propose companion scope inference: when an identifier X cannot be resolved through normal name lookup, and the surrounding position has a known expected type T, the compiler searches T's companion module for a term-level member named X.

It should be clarified what exactly the "surrounding position" is. For cases like this it's obvious:

val x: Color = Red

Here, the expression of which we know the expected type is just the identifier Red
But in a case like this it's less obvious:

val x: Animal = Dog("Fido")

The expression Dog("Fido") isn't just an identifier. It's an Apply node, the first child node of which is the identifier Dog. But the sensible "surrounding position" in this case clearly isn't the position of the Dog node itself, it's the position of the Apply node, because that's the node that we know the expected type of.

So we need a clear rule to specify what exactly the "surrounding position" is. As @lihaoyi pointed out above, we already have rules for _ lambda expressions for this, but unfortunately I don't think they fit this use case exactly and we'll have to tweak them a bit.

@lihaoyi said that "they resolve to the nearest enclosing parentheses". That's not quite correct. It holds for e. g. f(_ + 1) because the surrounding position in this case is the position of f's parameter. But it doesn't hold for f(_), because the surrounding position in that case is position of the call to f itself, not of f's parameter. That's clearly not suitable for this SIP because it means that the trivial example of val x: Color = Red wouldn't work and you'd have to write something stupid like val x: Color = identity(Red). So the rules will need to be slightly different from the rules for lambdas. Probably we should really use the "nearest enclosing parentheses" rule for this case, and not deviate from it like _ lambdas do.

@raquo

raquo commented May 14, 2026

Copy link
Copy Markdown

(First a couple notes about my Laminar use case to close that branch of discussion, but then back to this SIP below.)

I assume for your use case you would do an export Button.* inside the Modifier companion object.

@lihaoyi I see, basically move variant et al from object Button to a new object Modifier inside Button, with a new corresponding trait Modifier in Button instead of Laminar's generic Modifier.

Practically, I don't think that would work, because:

  • Such a Button-specific Modifier would need to re-implement all of Laminar's methods like := and --> that create generic modifiers.
  • Or I would need to make Laminar's entire API generic in the subtype of Modifier so that it can be brought into every component like Button – but that's not feasible, the abstraction complexity is not worth it
  • Even if I did, we still want Button.of to accept generic Laminar modifiers (like cls := "foo) that were created outside of the Button API, but now it won't be able to.
  • Perhaps we could use a union type of Button.Modifier | Laminar.Modifier to accept both params, but this seems like a worse option than what I have right now. I would lose the _. part of the syntax that helps reading ergonomics & autocompletion, gain the efficiency of plain values instead of functions, and lose in additional implementation complexity. Overall it's a net loss to me.

Would the "path-shape completion" idea be too verbose for Laminar?

@bjornregnell If you mean syntax like *.*.Dog for nested enums, I don't think that matches my Laminar use case. I don't have nested enums, my chaining is because I'm using methods like := / apply / -->, the intermediary links of the chain can't be shortened to *, only the root of the chain can be, in my case.

I understand that what I asked for originally does not fit the purpose of this proposal, especially if it's made to be about import resolutions, not new syntax. I just wanted to bring up a related need, but it turned out to be too hard / not related enough. That's fine.

As it stands, this proposal won't affect my current usage patterns in the Laminar ecosystem that I brought up – as Martin sad, _. lambda syntax seems to be the better solution for me. I've come to realize that I would find the status quo a lot more palatable if IntelliJ actually supported autocomplete for union type arguments involving function types (e.g. def of(arg: Modifier | Button.type => Modifier) won't autocomplete anything when typing of(_.)) – but of course that has nothing to do with Scala language itself.


Back to this SIP – now without sigils, this proposal seems a tad too magicky and undiscoverable. Existing scoping rules work with visible markers – import statements, class declarations, etc. They might not always tell you which exact values they make available (if you import * or if you class extends a trait from a different file), but it's visually clear in which exact scope those values are available.

Compare that to calling useColor(Red) – you have no idea that special scoping rules are in effect for that Red value. It does not make sense that you can't refactor it to say val color = Red; useColor(color). It only makes sense if you consider every argument passing, and every type-ascribed declaration, to be its own scope.

But that would be so mentally exhausting. Existing scopes that bring in unmentioned values (e.g. wildcard imports, inheritance) are few in a given file, and are very large – typically entire file for import-s, entire class body for all inherited members, etc. Whereas this sigil-less SIP would make every Scala file peppered with bespoke scopes that bring in additional values only available in very narrow locations in the file.

Currently if I start typing useColor(Re), IntelliJ autocomplete will suggest this Red, and if I accept it, it will import that value[1]. The initial writing experience after this SIP will be the same as status quo if you use autocompletion, except there will be no import. But refactoring such code will become more burdensome. You can say – well how hard is it to import Red after refactoring – actually it's quite a bit more cumbersome than importing it from the original autocomplete, which requires no extra actions compared to using autocomplete with this SIP. But when refactoring with this SIP (e.g. to write val color = Red; useColor(color)), you need to see your refactored code become red, wait for the IDE to recognize where it can import Red from, and only then can you finally trigger the import popup and select the import.

I don't know if the extra mental overhead is worth it. I can see pros and cons, but seems tenuous. I do like to use enums, but not enough for imported name collisions and namespace pollution to be a bigger problem than the mental overhead of numerous highly granular scopes with no visual markers.

[1] in fact it's quite maddening that it will NOT suggest to import Color even if I start typing useColor(Colo, but again, not Scala's fault.

@arturopala

Copy link
Copy Markdown

now without sigils, this proposal seems a tad too magicky and undiscoverable. Existing scoping rules work with visible markers – import statements, class declarations, etc. They might not always tell you which exact values they make available (if you import * or if you class extends a trait from a different file), but it's visually clear in which exact scope those values are available.

Matter of taste. I personally would love a companion object concept to play a more prominent role in Scala's scoping rules and to effectively reduce the need to import closely related stuff on every corner. A companion object could be a first place to look for if something feels magical, similar to implicit resolution.

@lihaoyi

lihaoyi commented May 14, 2026 •

Copy link
Copy Markdown
Contributor

From my perspective, one open-point for discussion is the failure within context of equality. Do we want some specialization to enable color == Red to compile?

I just found that Dart does have special casing for this, called Asymmetric Equality Tests. Dart is a relatively similar language to Scala - hybrid OO/FP, universal equality, etc. - so maybe it could be worth doing the same thing

The == and != operators have a special rule for dot shorthands. When dot shorthand syntax is used directly on the right-hand side of an equality check, Dart uses the static type of the left-hand side to determine the class or enum for the shorthand.

For instance, in an expression like myColor == .green, the type of the variable myColor is used as the context. This means the compiler interprets .green as Color.green.

enum Color { red, green, blue }

// Use dot shorthand syntax for equality expressions:
void allowedExamples() {
  Color myColor = Color.red;
  bool condition = true;

  // OK: `myColor` is a `Color`, so `.green` is inferred as `Color.green`.
  if (myColor == .green) {
    print('The color is green.');
  }

  // OK: Works with `!=` as well.
  if (myColor != .blue) {
    print('The color is not blue.');
  }

  // OK: The context for the ternary is the variable `inferredColor`
  // being assigned to, which has a type of `Color`.
  Color inferredColor = condition ? .green : .blue;
  print('Inferred color is $inferredColor');
}

The dot shorthand must be on the right-hand side of the == or != operator. Comparing against a more complex expression, like a conditional expression, is also not allowed.

static analysis: failure
enum Color { red, green, blue }

void notAllowedExamples() {
  Color myColor = Color.red;
  bool condition = true;

  // ERROR: The shorthand must be on the right side of `==`.
  // Dart's `==` operator is not symmetric for this feature.
  if (.red == myColor) {
    print('This will not compile.');
  }

  // ERROR: The right-hand side is a complex expression (a conditional expression),
  // which is not a valid target for shorthand in a comparison.
  if (myColor == (condition ? .green : .blue)) {
    print('This will not compile.');
  }

  // ERROR: The type context is lost by casting `myColor` to `Object`.
  // The compiler no longer knows that `.green` should refer to `Color.green`.
  if ((myColor as Object) == .green) {
    print('This will not compile.');
  }
}

@soronpo

soronpo commented May 14, 2026

Copy link
Copy Markdown
Contributor Author

From my perspective, one open-point for discussion is the failure within context of equality. Do we want some specialization to enable color == Red to compile?

I just found that Dart does have special casing for this, called Asymmetric Equality Tests. Swift is a relatively similar language to Scala - hybrid OO/FP, universal equality, etc. - so maybe it could be worth doing the same thing

The == and != operators have a special rule for dot shorthands. When dot shorthand syntax is used directly on the right-hand side of an equality check, Dart uses the static type of the left-hand side to determine the class or enum for the shorthand.
For instance, in an expression like myColor == .green, the type of the variable myColor is used as the context. This means the compiler interprets .green as Color.green.

Interesting. If we do this in Scala it will be exactly the same restriction

@bjornregnell

bjornregnell commented May 15, 2026 •

Copy link
Copy Markdown

I just re-read the latest update of this non-sigil version and I first must say that @soronpo have made a very thorough and pedagogical write-up of the different trade-offs and pros/cons - many thanks!!

I'm currently on the fence but leaning towards this priority in my ranking/voting on options: 1) non-sigil 2) staus quo 3) sigil; mainly because I think the use cases that need less boiler-plate are important and I want to avoid cryptic syntax while keeping existing code unaffected. What could change my mind is if the dangers are shown to be too high, but the arguments made in the proposal that good diagnostics will help seems fine.

If we go with the non-sigil option then we have all these benefits: more things will compile but no existing code will break and the code looks the same as if some import boiler-plate was written explicitly, and all this without any new syntax.

@kyouko-taiga

Copy link
Copy Markdown
Contributor

Here's my last ditch effort to change the course of history ;)

mainly because I think the use cases that need less boiler-plate are important and I want to avoid cryptic syntax while keeping existing code unaffected.

The proposal mentions 7 languages that have special syntax for the feature being discussed, 4 of which are inarguably more popular than Scala, and 3 of which have been using a leading sigil in production for years. I can perfectly understand that people don't like the syntax and that doesn't require any justification. But saying that it is cryptic is a bit of a stretch.

While I personally loathe Scala's use of _ in closures with a burning passion and find it nonsensical, I can hardly say it is cryptic, as I very seldom have to decipher what it means. Syntax is only cryptic if it negatively impacts legibility in spite of experience. It is only very anecdotical, of course, but after 9 years of active participation in the Swift community, I honestly can't remember any serious criticism about its leading dot.

As the proposal acknowledges, I don't think it is fair to deny that the use of a sigil at the use site has merged the mainstream at this point, regardless of how we feel about it.

What could change my mind is if the dangers are shown to be too high, but the arguments made in the proposal that good diagnostics will help seems fine.

Fixing the weaknesses of a design with error messages two issues:

  1. We have to find an error to diagnose in the first place.

Imagine we write the following:

enum Direction:
  case Up, Down, Left, Right
def move(d: Direction): Unit = ???

move(Down) // Yeah, that works!

For some reason, the user decides to inline the direction.

val d = Down // Oh no!
move(d)

Obviously we can't hint that full qualification was necessary here, otherwise every lookup error would need 3 pages of hints. So there's no error to guide the user. It's just one more wrinkle to teach.

How bad is it? Well, it adds up. What makes a language hard to read is rarely a single particular thing but rather a constellation of asterisks we have to add to big nice rules, like "one can factor out any subexpression". Sure, implicit resolution and widening already break this rule, but I don't think that justifies adding an exception.

Isn't the example ill-typed anyway? Sure, inlining .Down won't work either but at least there's a way to explain what's going one more precisely. That's clearly better because it shows why the magic trick doesn't work in this particular instance. At the risk of obnoxiousness, I'll show the error in Swift:

let d = .down
         ˄˜˜˜˜
         ╰─ error: reference to member 'down' cannot be resolved without a contextual type
  1. We have to burden existing diagnostics with additional information, just in case.

The proposal mandates that several errors be now accompanied by additional hints to help the user in case they intended to use the new feature. These additional hints will be helpful but come with cognitive overload costs. They will also add noise when the feature was not intended to be used.

Here's one example given in the proposal:

Type mismatch.
  Expected: Shape.Geometry
  Found:    Triangle (of type Triangle in scope at line N)
  Note: Shape.Geometry's companion also has a member named Triangle;
        if you meant that, qualify it as Shape.Geometry.Triangle.

That is a quite long message if you ask me. We're diluting useful information into a lot of text that brings two new concepts into the discussion that may or may not be relevant. And the types are simple here; no generics in sight. Here's what a type mismatch look like in my daily use:

[E007] Type Mismatch Error: Parser.scala:67:10 
|          lhs
|          ^^^
|Found:    (lhs : yafl.syntax.Syntax[yafl.syntax.TermTree])
|Required: yafl.parser.Parser.Result[yafl.syntax.Syntax[yafl.syntax.TermTree]]

Frankly, I find it already difficult to work with this error message. I won't like the two extra lines of text telling me about what was or wasn't found in my companion objects.

This example is not artificial and hasn't picked out of nowhere. Pardon my perhaps foreign use of scoping but here's how I set up some of the types involved in the above message:

case class Syntax[+T](val value: T, val span: SourceSpan)

sealed trait TermTree
object TermTree:
  case class Variable(name: String) extends TermTree

sealed trait TypeTree
object TypeTree:
  case class Variable(name: String) extends TypeTree

And naturally I'll be happy to write val x: Syntax[TermTree] = Syntax(Variable("x")).

By the way, this example also shows once more (if that was necessary) why importing everything into a single scope does not work in legitimate use cases. I do want to name term and type variables with just Variable but having to qualify every use is noisy.

If we go with the non-sigil option then we have all these benefits: more things will compile but no existing code will break and the code looks the same

The main utility of type checkers is about what they reject, not what they accept. The more clever we make them, the harder it becomes for them to diagnose what's wrong. This struggle is not new. Heavy use of inference makes code concise but also tend to yield poor error messages. So we add constraints (often via syntax) to narrow the scope of what could possibly have been intended.

@bjornregnell

Copy link
Copy Markdown

For some reason, the user decides to inline the direction.

val d = Down // Oh no!
move(d)

Wouldn't a val with explicit target type work? @kyouko-taiga

val d: Direction = Down
move(d)

@bjornregnell

bjornregnell commented May 16, 2026 •

Copy link
Copy Markdown

Here's my last ditch effort to change the course of history ;)

Yes we are history in the making :)

Thanks @kyouko-taiga for the thorough explanation of the problems. I agree that "cryptic" is in the eye of the reader, but I find both leading dot and leading hash strange-looking and the implicit name import based on target type a more Scala-natural syntax. Already today I sometimes suffer from my IDE randomly importing java stuff that happens to be called the same names that I'm using, which is an irritating surprise as I need to travel all the way to the top of the file to find out, but not too bad and rare enough. I wonder if we can somehow empirically assess the surprises.

@kyouko-taiga Your examples show how non-compiling code is a surprise, but that is at least less bad than compiling code that is not what was intended, and if I understand the non-sigil proposal correctly, that kind of name injection has the least priority and thus current naming rules should kick in as usual so no surprise there. Or have I misunderstood it?

@arturopala

Copy link
Copy Markdown

Each new language feature shapes the way we use that language to express something. I believe companion scope inference addition can positively change one important aspect of ergonomic writing of a Scala code: there might be much less to explicitly import, which always is kind.of a spanner put in the works, pure distraction and a problem when refactorinng. Ideally most libraries should be possible to use with just a single non-complicated import statement.

@kyouko-taiga

Copy link
Copy Markdown
Contributor

Wouldn't a val with explicit target type work?

Yes, but that's beside my point. My argument is that, if one just factors out a subexpression involving name lookup tricks, the error message they'll get won't tell them why the transformation failed. A dedicated construct would.

So we're losing an opportunity to teach the user about some understandably surprising behavior, namely an exception to the rule that says one can factor out any subexpression into a val. As I said, that's one more thing to teach.

[...] if I understand the non-sigil proposal correctly, that kind of name injection has the least priority and thus current naming rules should kick in as usual so no surprise there.

As I pointed out, the ability to accept a program is not the be-all and end-all. It is also at least as valuable for a compiler to be able to tell as precisely as possible why something is wrong, to keep diagnostics concise and reduce cognitive overload. Casting a wide net on the set of possible intents works against this objective. It will inevitably produce error messages containing needless information with respect to a specific situation. That can't be good for humans, and neither for LLMs (since it's seemingly become a criterion these days).

As I mentioned in an earlier post, one big objection I have to the proposed solution is that it is not easily discoverable. Moreover, it requires a solid understanding of Scala to explain while simultaneously polluting (decidedly a theme in this whole proposal 😅) possibly unrelated error messages.

I don't want to re-hash my points or the ones that have been shared by others so I'll refrain from posting other examples; there are plenty in the proposal and the thread already. However, I would encourage one to look beyond the mere ability to have a program type check and consider the user's experience discovering the feature and its underlying rules. I don't think we should shrug off all cases where the trick doesn't work just because full qualification can resolve the ambiguity.

I'll also point out that, while I am utterly and irrevocably convinced that a sigil is an unambiguously (😉) superior choice, I understand this ship will never sail and am just pleading for the status quo.

@scala scala locked and limited conversation to collaborators May 18, 2026
@soronpo

soronpo commented May 18, 2026

Copy link
Copy Markdown
Contributor Author

Locked until rewrite and official review is done.


The same pain appears beyond ADTs whenever a companion holds factory members (e.g., in DSL builders) or when opaque types wrap existing enums. In every such case the call site already knows the expected type; what it lacks is a way to *reuse* that knowledge to look up the member by its short name.

### Empirical analysis: how often would companion scope inference fire?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

While interesting and useful, I'm not sure the empirical analysis really fits into the SIP. It takes quite a bit of space in the text and contains links that can easily become dead in a few years. I think the final text should just describe that it was done and what the results were in a footnote.

1. **Member not in the expected type's companion.** When normal resolution fails and companion lookup also fails, the error names the companion that was searched and lists the closest available members:
```
Not found: Triagle
Searched expected type Shape.Geometry's companion.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The linked impl doesn't always succeed here (see example above with val c3: Seq[(Int,Int)] = (fill(3)(1)).zip(fill(3)(2))).

Generally I'm a bit worried that this pollutes diagnostics. This isn't as bad as C++ failed template resolution errors obviously, but it has some of the same "character". You go from a fairly straightforward "Not found X" error to something more complex.

The sigil version wouldn't have that issue because you wouldn't need a special diagnostic anyway.


The rule does not pre-filter by conformance; the resolved member's type may differ from `T` and a `given Conversion` (or other conversion) is expected to bridge the gap.

Only the static expected type's companion is searched, not its supertypes' companions. A user who needs a member from a supertype writes the chained form (see the *Animal* worked example), or qualifies explicitly.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If anything, it's subtypes that should be searched anyway, because this is really a contravariant site. This is of course impossible although it would fix the Seq.flatMap problem.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've played around with the implementation. I think it's generally a very useful feature. It would help significantly with reducing import clobbering in all kinds of libraries. It would make a lot of code easier to read. It's composable. It could even be used to implement most of the collection literals syntax without much compiler magic (but with some controversial modifications to the sip, such as allowing apply.)

In my opinion (and I'm sorry for reopening that bike shedding discussion), the sigil-based (or leading-dot, or keyword etc.) approach is the better one. All the examples I give in this review would be simpler (and produce better diagnostics) with a sigil form that explicitly tells the compiler that you want the companion object expansion. The sigil being replaced by the companion object would be an actually uniform mental model. In fact, you could think of the sigil as being just a type alias for the companion of the expected type and everything would work (including extension methods). Using the sigil where there isn't a companion object would just produce a not found error for the companion object without the need for additional diagnostics.

As of today, I think the sigil-less version of the SIP has too many corner cases, but that we should seriously consider the sigil form. I for one do not care particularly what the sigil is. I would also be happy with a keyword (type., object.) which maybe doesn't save characters, but would make some code nicer to read anyway,

class A(m: Map[String, String], j: Seq[String], k: Option[Boolean])
val x = A(type.empty, type.empty, type.empty)

3. **If found**, use the member as if the user had written `T'.X` explicitly. The resolved expression is then re-typed by the language's normal `Select` machinery, including implicit conversions.
4. **If still not found**, emit a "not found" error, possibly enriched with the companions searched (see *Diagnostics*).

The mental model is uniform: *"the bare `X` of whatever type is expected here, if `X` is not otherwise in scope."*

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The "simple mental model" of inserting A.x where an A is required and an x is found is incomplete with respect to extension methods. I believe this is as spec-ed here, not an implementation bug. For example,

trait Factory[T]:
  val instance: T

extension[T] (f: Factory[T])
  def createOne: T = f.instance

class A
object A extends Factory[A]:
  val instance = new A

def needsA(a: A) = ???

val a = needsA(instance) // works
val b = needsA(A.createOne) // works
val j = needsA(createOne) // doesn't work

The error in this case isn't great either (because createOne as Factory[Any] => Any is in scope),

[error] ./Test.scala:20:16
[error] Found:    Factory[Any] => Any
[error] Required: A
[error] val j = needsA(createOne) // doesn't work
[error]                ^^^^^^^^^

This makes it a lot less uniform than claimed here.


## Summary

We propose **companion scope inference**: when an identifier `X` cannot be resolved through normal name lookup, *and* the surrounding position has a known expected type `T`, the compiler searches `T`'s companion module for a term-level member named `X`. If such a member is found, the use site is treated as if the user had written `T.X` explicitly.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One issue I have with the proposed syntax is that it doesn't always play well with generics in ways that I think can be surprising. For example, this compiles correctly

val x1 = Option(1).flatMap:
  case i if i % 2 == 0 => Some(i)
  case _ => empty

but this doesn't

val x2 = Seq(1,2,3).flatMap:
  case i if i % 2 == 0 => empty
  case ow => Seq(ow)

because Seq.flatMap is actually IterableOps.flatMap and so it takes an IterableOnce[T] and there isn't an IterableOnce.empty.

Similarly, this works,

val a: Seq[Int] = fill(3)(1)
val b: Seq[Int] = fill(3)(2)
val c: Seq[(Int, Int)] = a.zip(b)

And so does this,

val c2: Seq[(Int,Int)] = (fill(3)(1)).zip(b)

but not

val c3: Seq[(Int,Int)] = a.zip(fill(3)(2))

In the later case, you get this error

[error] Not found: fill - did you mean Null?
[error] val c3: Seq[(Int, Int)] = a.zip(fill(3)(2))
[error]                                 ^^^^

which for reasons that are not entirely clear to me doesn't actually say anything about companion objects.

- **Costs (acknowledged)**
- The reader cannot tell at a glance whether a bare `Red` was resolved in lexical scope or via the companion. Under the `#X` draft the leading sigil provides that anchor; this draft does not.
- *Silent shadowing* is possible: when a bare `Triangle` happens to resolve to a local of an unrelated type, the user receives a type-mismatch error rather than the "look in the companion" hint they would have received under a sigilled form.
- Adding a member to a companion can make previously-erroring code compile (it cannot, however, change the meaning of code that already compiled; see *Compatibility*).

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MINOR: I don't think that's right.

Consider

final case class C[T](value: T)
object C:
  def forSeq[A]: C[Seq[A]] = C(empty)

@main def main(): Unit =
  println(C.forSeq[Int].value.isEmpty) // prints true

Someone comes in and decides (for some reason) to add def empty = ??? to the object C (or to one of its super class) and now the code throws, because empty resolves to the empty: Nothing def. (This is also possible with the import, so it's not exactly new.) I guess the comment should really be saying that it won't change the meaning of code outside the companion object.

The sigil version here (def forSeq[A]: C[Seq[A]] = C(#empty)) would actually be more robust than importing Seq.empty as it would be as explicit as referring to Seq.empty directly.

render(text("hi")) // companion scope inference: text → Frag.text
```

The companion's `apply` method is not given special status. `Color(20, 5, 100)` already works under existing Scala rules because `Color` is a type in scope, so its companion's `apply` is reached by the standard apply-method dispatch. Inside an enclosing scope where bare `apply` resolves to *some other* `apply` (for example a containing `object Foo`), companion scope inference does not silently rescue the call site; the user qualifies the call as `Color.apply(...)` or `Color(...)` explicitly. This is the same disambiguation step the language already requires when two methods named `apply` are visible.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think support for apply would be great for the sigil form. Then you could do

val x: Seq[Seq[Int]] = #.(#.(1, 2),  #.(3))

This would cover a lot of the grounds of collection literals. It doesn't really work for the bare version though.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.