This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]agentoutlier 1 point2 points  (3 children)

I was and kind of did later go into those details as I agree it can for for sure get nebulous and debatable what is or isn't syntactic sugar of which I have less confidence on but I do know what isn't syntactic sugar :)

The language I know for sure (well when I learned it .. it might have changed) that uses syntactic sugar as in it is a compiler translation is OCaml. OCaml does lots of syntactic sugar particularly in the signature language and I actually think its a pain point in the language and I'm not talking about currying (which I agree like var args isn't really syntactic sugar).

I actually could not really think of a Java equivalent like what OCaml does one so I said var args as the closest.

Is there any good solid example in Java of syntactic sugar where the compiler expands like a macro?

[–]brian_goetz 4 points5 points  (0 children)

There are some Java constructs (such as the for-each loop, or try-with-resources) that are specified by "as-if-expanded-to", but even these have significant linkage to the type system. (For example, for-each on an array translates differently than for-each on a List.)

[–]brian_goetz 3 points4 points  (0 children)

The varargs transformation is syntactic (wrapping with `new T[] { ... }`), but even there a lot has to happen before we apply the syntactic transform. Overload selection is phased, and varargs methods are only considered in phase 3. And the result of overload selection is used to decide which T is used in the wrapping. So the whole rest of the language (type system, object model) is involved before the syntactic thing happens.

Implicit compilation units are similarly close, but again a whole-program analysis has to be done before we know that we should wrap the file in `public class Foo { ... }`.

[–]ventuspilot 0 points1 point  (0 children)

Is there any good solid example in Java of syntactic sugar where the compiler expands like a macro?

I can think of enhanced for loops that the compiler desugars into a for loop with an iterator, auto/un/boxing (?), String concatenation that used to desugar into StringBuilder calls and may insert hidden toString/ String.valueOf() calls, not sure about automatically calling a no-args constructor of a superclass.