4

Almost every book introducing lambda beginning with a Runnable anonymous class, or even mentioned as an alternative to "anonymous class". However, lambda returns the same object while anonymous class returns a new one.

1. Why lambda behaves like this?

2. Why it is designed to be so?

example codes and results

Tiina
  • 4,285
  • 7
  • 44
  • 73
  • I think the reason might be to add the possibility to chain-call methods using lambda, like lambda2(lambda()). – Lajos Arpad Sep 29 '17 at 09:16
  • 3
    Because you don’t need multiple instances of `Runnable` doing exactly the same thing. The anonymous inner class, however, is connected with the `new` operator, which guarantees to produce a new distinct instance, whether you need it or not. Lambda expressions opened to opportunity to create less objects, which has been explicitly declared in the specification. As explained in [Does a lambda expression create an object on the heap every time it's executed?](https://stackoverflow.com/q/27524445/2711488)… – Holger Sep 29 '17 at 11:10
  • 2
    Avoiding allocation is a Good Thing™, so there's little reason why it should behave any other way (although it could). – the8472 Sep 29 '17 at 13:52

1 Answers1

1

The CallSite is the same in your case, and linkage happens per call-site. I think, to better understand this you need to look at what invokedynamic is. You can read more here.

Eugene
  • 117,005
  • 15
  • 201
  • 306
  • 3
    No, regular developers should not have to understand the low-level mechanics (which are free to change!) in order to use lambdas effectively. What they have to know is: lambdas come with no guarantee of the uniqueness of their identity, full stop. – Brian Goetz Sep 30 '17 at 18:51
  • @BrianGoetz then that *regular developer* becomes an *exception bogglehead* because his/her unexpected situation may happen anytime anywhere. – Tiina Oct 09 '17 at 03:08
  • @Tiina Perhaps I wasn't clear; what I was criticizing was the answer, not the question. What regular developers should understand is that the _Java Language Specification_ says that lambda expressions do not make any commitment about their identity. The details of `CallSite` and `invokedynamic` are mere implementation details, which may change, as long as the implementation adheres to the specification. Users should understand what the _language commits to_, rather than what the _compiler happens to do on any given day._ – Brian Goetz Oct 09 '17 at 03:13