Two exact method references are not equal

java, java-8

Solution

Lambdas are not cached and this seems to be deliberate. There is no way to compare two lambdas to see if they would do the same thing.

You need to do something like

static final Function<String, Integer> parseInt = Integer::parseInt;

@Test
public void test() {
    Function<String, Integer> foo = parseInt;
    Function<String, Integer> bar = parseInt;
    assertThat(foo, equalTo(bar));
}

Answer from Brian Goetz; Is there a way to compare lambdas?

Problem

The following test fails ``` @Test public void test() { Function<String, Integer> foo = Integer::parseInt; Function<String, Integer> bar = Integer::parseInt; assertThat(foo, equalTo(bar)); } ``` is there any way to make it pass? edit: I'll try to make it more clear what I'm trying to do. Lets say I have these classes: ``` class A { public int foo(Function<String, Integer> foo) {...} } class B { private final A a; // c'tor injected public int bar() { return a.foo(Integer::parseInt); } } ``` now lets say i want to write unit test for B: ``` @Test public void test() { A a = mock(A.class); B b = new B(a); b.bar(); verify(a).foo(Integer::parseInt); } ``` the problem is that the test fails, because the method references are not equal.

Original source

Related problems