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
3
  • 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. Commented Mar 30, 2017 at 9: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.) Commented Mar 30, 2017 at 9:51
  • 4
    See Does a lambda expression create an object on the heap every time it's executed?. 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 which shows, under which circumstances the objects are the same in the current implementation. Commented Mar 30, 2017 at 12:26

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.