Stephen Colebourne's blog: December 2015
I discovered that Java 8 has a language feature I'd never heard of before today!
Explicit receiver parameters
Consider a simple method in Java 7:
public class Currency { public String getCode() { ... } }
In Java 8, it turns out there is a second way to write the method:
public class Currency { public String getCode(Currency this) { ... } }
The same trick also works for methods with arguments:
public class Currency { public int compareTo(Currency this, Currency other) { ... } }
So, what is going on here?
The relevant part of the Java Language Specification is here.
The receiver parameter is an optional syntactic device for an instance method or an inner class's constructor. For an instance method, the receiver parameter represents the object for which the method is invoked. For an inner class's constructor, the receiver parameter represents the immediately enclosing instance of the newly constructed object. Either way, the receiver parameter exists solely to allow the type of the represented object to be denoted in source code, so that the type may be annotated. The receiver parameter is not a formal parameter; more precisely, it is not a declaration of any kind of variable, it is never bound to any value passed as an argument in a method invocation expression or qualified class instance creation expression, and it has no effect whatsoever at run time.
Read full article from Stephen Colebourne's blog: December 2015
No comments:
Post a Comment