Search code examples
javalambdajava-8assertj

Ambiguous method call with Lambda in Java


I have defined a static assertThat method to extend AssertJ. This method accepts a lambda expression of the type:

@FunctionalInterface
public interface Action {
  void execute() throws Exception;
}

The signature looks like this:

public static ExceptionAssert assertThat(Action action)

I want to use this method with a static import. But it is ambiguous. The compiler doesn't know whether assertThat(Iterable) or my method should be used. I don't understand how a void method can conflict with a method that returns an Iterator<T>.

Any idea how to resolve this conflict (without writing the class name in front of assertThat)?


Solution

  • You should specify the type of lambda explicitly:

    assertThat((Action)() -> {
        ...
    });
    

    The other option is just using the other name, for example, assertNoException