2

Is

test::testMethod == test::testMethod

true? I want to find out whether they will refer to the same object. This code does not compile. But there may be several situations in which this needs clarification.

I suspect that this will expand to

Runnable r = () -> test.testMethod()
Runnable r1 = () -> test.testMethod()

And whether the below is true.

r == r1
Pinser
  • 1,898
  • 3
  • 29
  • 43
  • 6
    If the code doesn't compile, then asking whether the result is `true` or not is meaningless. Please provide a complete example that *does* compile. – Jon Skeet Mar 30 '17 at 09:49
  • 2
    I suspect the answer is that it's not specified though - JLS 15.13.3: "Next, either a new instance of a class with the properties below is allocated and initialized, or an existing instance of a class with the properties below is referenced." (With no details that I can see about the cases in which an instance is reused.) – Jon Skeet Mar 30 '17 at 09:51
  • 4
    See [Does a lambda expression create an object on the heap every time it's executed?](http://stackoverflow.com/a/27524543/2711488). In short, it’s intentionally unspecified. It might be `true`, but doesn’t have to. And in the current JRE, it isn’t. You may also retrace the test of [this answer](http://stackoverflow.com/a/23991339/2711488) which shows, under which circumstances the objects are the same in the current implementation. – Holger Mar 30 '17 at 12:26

2 Answers2

1

Let's look at the following example:

Predicate<String> predicate = String::isEmpty;

Function<String,Boolean> function = String::isEmpty;

System.out.println(predicate.equals(function)); // false

A lambda doesn't contain any information about it's type. That information is deduced from the context. The same lamba String::inEmpty can represent different functional interfaces, as we have seen above.

Anton Balaniuc
  • 10,889
  • 1
  • 35
  • 53
1

even if your code could compile and the test::testMethod declared as Runnable the answer test::testMethod == test::testMethod is always return false, because you comparing with two diff class instances. for each lambda expression the compiler will create a synthentic anonymous inner class for it.for example:

//a synthentic anonymous lambda class A implemented Runnable
Runnable r = () -> test.testMethod(); 

//a synthentic anonymous lambda class B implemented Runnable
Runnable r1 = () -> test.testMethod();

r.getClass().equals(r1.getClass());// always return false
holi-java
  • 29,655
  • 7
  • 72
  • 83