Method Chaining (enhancing Java syntax)

Maurizio Cimadamore maurizio.cimadamore at oracle.com
Tue Jun 13 18:03:32 UTC 2023


On 13/06/2023 18:17, Tomáš Bleša wrote:
> “/returns the same instance it is called on/”. The fact that it is 
> also the same type is a useful byproduct. Please note that I used 
> lowercase T to emphasize it is the instance not type.

I see what you mean, but what you are describing here is dynamic 
behavior - e.g. how a method with returning "this" should be evaluated. 
The question remains: what is the static type of "this" in a method 
declaration? The JLS and the compiler would have to define that, and 
that's why at some point you veer into self-type territory. Granted, you 
*could* define the static type of Foo::m where the method return "this" 
as Foo - e.g. a weaker self-type, which is derived from the receiver 
expression seen from the compiler.

Your translation strategy should not, thus, use "void" as a return type, 
but use whatever T the type is assumed to be at compile-time. There 
*has* to be a type there, otherwise it is not clear how the compiler can 
type-check a call to a method returning "this". This is not just about 
bytecode, and I believe your emphasis on coming up with a translation 
scheme which minimizes passing receiver back and forth might be 
misguided (after all, we have an optimizing compiler that will likely 
take care of that problem - via inlining - among other things).

As far as I understand, the possible benefits are:

* user can omit "return this" inside the method body
* covariant override are automatically added in subclasses

Note that a better way to achieve same benefits is with the "wither" 
approach proposed by Brian sometimes ago:

https://github.com/openjdk/amber-docs/blob/master/eg-drafts/reconstruction-records-and-classes.md

IMHO, that proposal addresses the issue of dealing with immutable data 
at a much deeper level.

Maurizio
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/jdk-dev/attachments/20230613/6f0175f5/attachment.htm>


More information about the jdk-dev mailing list