Is there a way to extend unnamed classes to somehow facilitate top level static methods in Java?

Brian Goetz brian.goetz at oracle.com
Wed Oct 18 14:14:26 UTC 2023


Let me separate your points a bit.

Are unnamed classes a form of free functions in disguise? Emphatically 
no.  There are class declarations there, you just don't have to 
explicitly type them, and they are not really supposed to escape their 
own compilation unit (clever programmers can make this happen, but 
that's not the goal.)

So let's rephrase your question to "I think free functions are cool, 
should Java have them?"  As you can probably imagine, this was discussed 
in the design of unnamed classes.

The main question surrounding free functions is scoping; when a 
compilation unit declares a free function, what is its scope? One 
obvious answer is "the compilation unit", but in this case, the feature 
offers us relatively little, just a choice of where to declare it.  This 
might be convenient in a minor way, but would surely not carry its 
weight.  (Remember, no feature is "small", and every feature carries 
risks of foreclosing on future, better features.)

The other choice is that free functions would be in scope in any class 
that imports the compilation unit declaring them (making them 
effectively global).  This offers more payback, but at a significant 
cost: namespace pollution, discoverability (how do I know what to 
import?), and readability (when I see a bare function name, how do I 
know how to interpret it?)  I don't think we'll be going down this route.



On 10/17/2023 11:34 PM, Julian Waters wrote:
> Hi all,
>
> Quick question: Java is often criticized for having too much emphasis 
> on Object Oriented Programming, with every method having to be marked 
> static repeatedly if one wants to opt out of OOP. Recently, unnamed 
> classes and instance main methods were released into Java 21, which 
> got me thinking: Can we somehow use them (unnamed classes) to 
> facilitate top level "classless" methods in Java? Obviously, the 
> methods would in actuality belong to the unnamed class and aren't 
> actually classless, and internally would be static to avoid relying on 
> object instances (since they're supposed to be top level). Whether or 
> not we'd want to support top level global variables this way too I 
> leave up to discussion. Or maybe there's a different way to have free 
> form methods (such as with Kotlin) without having to mark entire 
> utility classes as static somehow?
>
> Thoughts?
>
> best regards,
> Julian
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20231018/0a10fd82/attachment.htm>


More information about the amber-dev mailing list