Implicit classes and "this"


#1

I have a class called Route to represent an assigned route of flight for an aircraft. I want to add several plotting methods, but I don’t want to clutter the operational code with the plotting code, so I define an implicit class for the plotting code:

object RoutePlotting {
implicit class RoutePlotting1(self: Route) {…}
}

I called the constructor argument “self”. But ideally shouldn’t it be “this”? If it were “this”, I could move methods from the original class to the implicit class (and vice versa) without any changes. But as it stands now, I have to replace every instance of “this” with “self”. I came up with a little trick to partially solve the problem:

import self._

This allows me to remove “self.” from “self.someMethod”, but it does not replace a standalone “self” with “this”.

It’s a minor issue no doubt, but it seems to me that the syntax could allow the name “this” for implicit class constructor argument – or allow the name to be omitted and default to “this”. Am I missing something?


#2

Scala 3 is likely headed that way: https://github.com/lampepfl/dotty/pull/4114

“Inside an extension method, the name this stands for the receiver on which the method is applied when it is invoked … As usual, this can be elided,”


#3

oh, hot off the presses, there is a newer proposal on this as of one hour ago: https://github.com/lampepfl/dotty/pull/5114