I like @nafg’s analysis and this proposal in particular.
Like others, I don’t like the idea of using
_ for object fields, but @newhoggy’s argument here seems strong enough to deserve an answer.
That refactoring seems indeed reasonable. But going from
val _ = expr to
expr also seems reasonable (with different assumptions on
_), yet it must make the result of
Anyway, since that refactoring might seem reasonable enough to try it, it should preserve behavior or give a compile-time error—as it does now, so we should keep that. The best rationale is that local scope and class/trait/object scope are not actually the same in Scala after all—even though they’re both templates in terms of the spec.
If you still believe all templates should really be the same: you have a point, but the JVM is not the platform you want. The concept of template comes instead from other languages, where methods are classes and stack frames are objects, having local variables as fields, like in Smalltalk, Python, etc. The actual concept of template comes from research language Beta AFAIK, but the rest is more common. That approach is more consistent, but IMHO it leads to outlawing underscore-named variables altogether. And you can’t make local variables into object fields efficiently without VM support (assuming you’d want that, which is far from obvious).
Fun thing is, people learned in the '80s how to do efficient VM support for locals = fields, for efficient Smalltalk JITs, and Hotspot comes from a Smalltalk implementation, so I assume they just ripped out this support.