Repository navigation
Conversation
|
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 |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
Is lambda supported in if expressions?
There was a problem hiding this comment.
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@7516e4e5Refines 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
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
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
|
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 |
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. |
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. |
|
@soronpo What do you think about accepting only target typing for enums and no leading dot? |
|
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 |
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. |
|
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 |
|
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 😅 . |
|
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 While 10 years ago in 2016 I would agree that the dot-prefixed @soronpo maybe this should be included in the proposal as prior art? 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)
}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,
};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
};
}
inductive Bar where
| foo
def x : Bar := .footype.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,
};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 => ...,
} |
Yes, will do, thanks! |
|
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 Here are some options I find acceptable:
|
|
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 |
import some.lib.*
object Some:
enum Enum:
case Foo
def f(x: Some.Enum): Int = 0
f(Foo)Assuming Now let's compare with that: // ...
import Some.Enum.*
f(Foo)That doesn't work either. At least I'm being told A leading sigil solves this issue. 🤷♀️ |
The target type of |
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... |
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 |
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 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:
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. |
|
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 |
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. |
|
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. |
|
I find this wording a bit vague:
It should be clarified what exactly the "surrounding position" is. For cases like this it's obvious: val x: Color = RedHere, the expression of which we know the expected type is just the identifier val x: Animal = Dog("Fido")The expression So we need a clear rule to specify what exactly the "surrounding position" is. As @lihaoyi pointed out above, we already have rules for @lihaoyi said that "they resolve to the nearest enclosing parentheses". That's not quite correct. It holds for e. g. |
|
(First a couple notes about my Laminar use case to close that branch of discussion, but then back to this SIP below.)
@lihaoyi I see, basically move Practically, I don't think that would work, because:
@bjornregnell If you mean syntax like 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, Back to this SIP – now without sigils, this proposal seems a tad too magicky and undiscoverable. Existing scoping rules work with visible markers – Compare that to calling 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 Currently if I start typing 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 |
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. |
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
|
Interesting. If we do this in Scala it will be exactly the same restriction |
|
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. |
|
Here's my last ditch effort to change the course of history ;)
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 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.
Fixing the weaknesses of a design with error messages two issues:
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
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: 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: 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 TypeTreeAnd naturally I'll be happy to write 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
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. |
Wouldn't a val with explicit target type work? @kyouko-taiga val d: Direction = Down
move(d) |
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? |
|
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. |
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
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. |
|
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? |
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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."* |
There was a problem hiding this comment.
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 workThe 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. |
There was a problem hiding this comment.
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 _ => emptybut 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*). |
There was a problem hiding this comment.
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 trueSomeone 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. |
There was a problem hiding this comment.
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.
No description provided.