Anonymous value classes
Dan Smith
daniel.smith at oracle.com
Fri Jun 3 16:15:57 UTC 2022
Our javac prototype has long included support for a 'value' keyword after 'new' to indicate that an anonymous class is a value class:
Runnable r = new value Runnable() {
public void run() { x.foo(); }
};
Is this something we'd like to preserve as a language feature?
Arguments for:
- Allows the semantics of "I don't need identity" to be conveyed (often true for anonymous classes).
- Gives the JVM more information for optimization. If we don't need a heap object, evaluating the expression may be a no-op.
Arguments against:
- Opens a Pandora's box of syntax: what other keywords can go there? 'identity'? 'primitive'? 'static'? 'record'?
- Because there's no named type, there are significantly fewer opportunities for optimization—you're probably going to end up with a heap object anyway.
- Value classes are primarily focused on simple data-carrying use cases, but any data being carried by an anonymous class is usually incidental. A new language feature would draw a lot of attention to this out-of-the-mainstream use case.
- In the simplest cases, you can use a lambda instead, and there the API implementation has freedom to implement lambdas with value classes if it turns out to be useful.
- The workaround—declare a local class instead—is reasonably straightforward for the scenarios where there's a real performance bottleneck that 'value' can help with.
More information about the valhalla-spec-observers
mailing list