Ambiguous method call using Lambda in Java

I have defined the static assertThat method for the AssertJ extension. This method accepts a lambda expression like:

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

The signature is as follows:

 public static ExceptionAssert assertThat(Action action) 

I want to use this method with static imports. But this is ambiguous. The compiler does not know whether assertThat (Iterable) or to use my method. I do not understand how the void method can conflict with the method that Iterator<T> returns.

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

+6
source share
4 answers

You must explicitly specify the lambda type:

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

Another option is just another name like assertNoException

+11
source

I do not understand how the void method can conflict with the method that Iterator<T> returns.

The only way you can have such a conflict is when your lambda expression never ends normally, for example. ()->{ throw new RuntimeException(); } ()->{ throw new RuntimeException(); } or ()->{ for(;;); } ()->{ for(;;); } .

(or if your lambda expression consists of one method call that really returns Iterable )

For all other cases, you are right, there should not be such a conflict and, indeed, I could compile the equivalent code without any problems with jdk1.8.0_20 for regular lambda expressions (you did not include the code that causes the error in your question) .

If you are having a problem with a lambda expression that might end up fine and use the old jdk, you have encountered the error discussed here . This answer relates to the part of the language specification that defines the difference between void compatible and meaningful lambda expressions.

If you used another compiler or IDE, for example. Eclipse, make sure you are using the latest version and logging an error report if this error still occurs.

+1
source

I had the same problem with eclipse version 4.4.1
Upgrading to 4.4.2 enabled it.

0
source

I just ran into the same problem and, as in brafdlog, it is recommended to upgrade it to the new version of eclipse. Except in my case, I was already on 4.4.2 (Spring Tool Suite 3.6.4) and updated to the latest Eclipse Neon 4.6.1 patch.

0
source

Source: https://habr.com/ru/post/975300/


All Articles