You are not quite right since we have
- implicit conversions from
A
to B
that actually can bring A
's names to the B
's scope;
- explicit
this.type
type that can be B
in an implicit conversion above.
In current Scala it should look pretty wordy; it can look like this:
trait ThisFunction[A, +R] {
def apply(a: A)(implicit s: this.type => A = {_ => a}): R
}
Then, having e.g.
trait SomeBuilder {
def dup: Int
def str: String
}
we can define (again, very wordy for now)
val f: ThisFunction[SomeBuilder, String] = new ThisFunction[SomeBuilder, String] {
override def apply(a: SomeBuilder)(implicit s: this.type => SomeBuilder) =
this.str * this.dup
}
As you can see, SomeBuilder
's names are brought to the scope of defined “function” f
(like you wanted). You can check that this really works.
(By the way, eliminating this
in the body does not work, but it looks rather like a bug.)
But this is not exactly what was wanted. But, it seems that Dotty’s implicit function types really can solve this problem exactly in the manner that was requested.
(Notice that there is a special ImplicitConvertions
type for implicit conversions in Dotty instead of just implicit function usage in Scala 2.)
We could have something like this in Dotty:
trait ThisFunction[A, +R] extends (A => (implicit ImplicitConverter[this.type, A] => R)) {
override def apply(a: A)(implicit ic: ImplicitConverter[this.type, A] = { _ => a }): R
}
It means that definition of an instance of this type of function does not require a boilerplate with new ThisFunction
and override def apply
, so it could be done in a manner like this:
val f: ThisFunction[SomeBuilder, String] = { a: SomeBuilder => str * dup }
But at the moment it seems to be not working since at least strange currying rules: override def apply
does not seem to override those apply
from the A => (implicit ImplicitConverter[this.type, A] => R)
type. This could probably be dictated by efficiency of compiled code (since def f(a: A)(b: B) = ...
is not the same as def f(a: A) = {b: B => ...}
), but it is not obvious that this should influence the language semantics. Thus, the fact that it’s not working now, can be a bug.
Nevertheless, my message is that implicit functions and implicit function type seem to be somehow helpful in your issue. And maybe Dotty will have enough for you to not to require syntactic changes and SIPs.