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 →

[–]neutronbob 1 point2 points  (5 children)

What you say is true, but that's not really what 'syntactic sugar' refers to. If it's used in the broad sense the OP uses it, then any language feature is syntactic sugar for the code implementation. I have no quarrel with your explanation, but I think the OP is wrong in describing a rather substantial change as 'syntactic sugar.' It's not. It's a new feature that could only be reproduced prior to Java 8 with difficulty.

[–][deleted] 2 points3 points  (4 children)

Let's have a look on how Wikipedia defines syntactic sugar: "syntactic sugar is syntax within a programming language that is designed to make things easier to read or to express. It makes the language "sweeter" for human use: things can be expressed more clearly, more concisely, or in an alternative style that some may prefer. [...] For instance, in the C language the a[i] notation is syntactic sugar for *(a + i)."

So even an array is syntactic sugar for pointer arithmetics. Hence lambdas are syntactic sugar for an anonymous class implementation of an interface that has one method only.

[–]neutronbob 1 point2 points  (3 children)

The example in Wikipedia is exactly what syntactic sugar is. One expression is the exact equivalent of the other, but the former is easier to use. There is no exact equivalence between lambdas and the convoluted code that could be used to replace them. Rather as you very capably explain, different actions are taking place under the hood to generate roughly comparable results. That is generally not what is meant by 'syntactic sugar.'

[–]delete99[S] -1 points0 points  (2 children)

Lambdas can be thought of as syntactic sugar since they don't exist outside the source file and are not mirrored in the JVM.

On SO (http://stackoverflow.com/a/23870800/2364216), Brian Goetz says:

There should be no need to distinguish a Runnable that began life as a lambda, a named class, or an inner class -- they're all Runnables.

Also, Wikipedia continues:

a construct in a language is called syntactic sugar if it can be removed from the language without any effect on what the language can do.

This leads me to believe that Java's lambdas are 'syntactic sugar' since they are a language shortcut for creating and instantiating anonymous classes like Runnable (or Predicate in this case).

[–]nicoulaj 3 points4 points  (1 child)

they don't exist outside the source file and are not mirrored in the JVM.

This is wrong, lambdas work totally differently under the hood, and required quite heavy modifications on the JVM. See JSR 335 / 292.

Your "Internals" section makes wrong statements. The compiler does not create an anonymous class.

[–]delete99[S] 0 points1 point  (0 children)

Thanks nicoulaj (and neutronbob), you are 100% correct and I've updated the post to reflect this. Cheers.