I appreciate the arguments given above for why we can’t readily support import at the top of an extension “block” as I’d initially suggested.
However, I do think there may be a case for an import syntax specifically targeting the members of the extension parameter, eg:
extension (import x: X)
def f
def g
or alternately:
extension import (x: X)
def f
def g
The effect would be for compiler to insert import x.{*, given}
at the top each extension method.
I first came to Scala, and still prefer it today, because the language offers industry-leading capabilities for factoring out shared structure in programs. The ability to extract common structure in code is what underlies Scala’s conciseness, productivity, and “convenience”, in my view.
Here we have an emerging example of common structure in a relatively young feature, extension methods. In object-oriented languages, references to an instance’s this
pointer are considered so common that they are typically resolved implicitly. Extension methods associated with a parameter likely need to make similarly frequent reference to members of that parameter.
“Good” code typically has many small methods, and so the overhead of an import statement at top of each method is significant; it was personally working on an extension with 10 methods, each 1-2 lines long, that first drove me to post this topic.
In terms of precedents, Kotlin’s extension methods implicitly import the members of the extended instance:
class Circle (val radius: Double) {
}
fun main() {
fun Circle.perimeter(): Double {
return 2*Math.PI*radius;
}
}
While in Swift and C# the extended parameter must be explicitly referenced.