"The target type of this expression must be a functional interface" even though it is

huangapple go评论79阅读模式
英文:

"The target type of this expression must be a functional interface" even though it is

问题

好的,下面是你要翻译的内容:

好吧,我感觉自己相当愚蠢。今天在我的Eclipse中遇到了这个问题,但无论如何我都想不出问题在哪里。

问题非常简单。以下代码可以编译通过:

MockCreationListener l = (mock, settings) -> {};
Mockito.framework().addListener(l);

以下代码无法通过编译:

Mockito.framework().addListener((mock, settings) -> {});

我已经知道这是我忽视的一些愚蠢问题,但这两段代码之间有什么区别呢?

英文:

Okay so I'm feeling pretty dumb here. I ran into this problem in my Eclipse today and for the world I can't figure out what the problem is.

It's very simple. The following compiles:

MockCreationListener l = (mock, settings) -> {};
Mockito.framework().addListener(l);

The following does not:

Mockito.framework().addListener((mock, settings) -> {});

I know already that this is some silly thing I overlooked but what is the difference between these two bits of code?

答案1

得分: 2

这是因为 addListener 接受一个 MockListener 接口。该接口是一个没有方法的标记接口。

正如您所知,Lambda 表达式只能转换为具有恰好一个抽象方法的接口。因此,Java 无法将您的 Lambda 表达式转换为 MockListener。在没有其他信息的情况下,它不知道应该将您的 Lambda 表达式转换为哪个功能接口,因此会输出错误。

当然, 知道它应该是 MockCreationListener,但编译器不能仅仅通过查看上下文来弄清楚这一点。就编译器而言,它可以是实现了 MockListener、同时接受两个参数并返回 void 的任何内容。

英文:

This is because addListener accepts a MockListener interface. which is a marker interface with no methods.

As you may know, lambdas can only be converted to interfaces with exactly one abstract method. So Java can't convert your lambda to MockListener. Without any other information, it doesn't know what functional interface it should convert your lambda to, so it outputs an error.

Of course, you know that it should be MockCreationListener, but the compiler can't figure it out just by looking at the context. It could be anything that implements MockListener and also accepts two parameters and returns void, as far as the compiler is concerned.

答案2

得分: 1

好的,以下是翻译好的内容:

我解决了它。

为了后人,答案是 Mockito.framework().addListener() 期望一个 MockListener 接口,而不是一个 MockCreationListener。

为什么这很重要?因为 MockCreationListener 定义了 lambda 实现的方法,而 Java 并不知道该 lambda 也是 MockListener 的有效实现——后者没有任何方法。

我正在关闭它,并为浪费大家的时间道歉。

英文:

Well I solved it.

For posterity the answer is that Mockito.framework().addListener() expects a MockListener interface, not a MockCreationListener.

Why is that important? Because MockCreationListener defines the method being implemented by the lambda and java has no idea that the lambda is also a valid implementation of MockListener - which has no methods.

I'm closing it and apoligies for wasting everyone's time.

huangapple
  • 本文由 发表于 2020年8月21日 16:25:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/63519225.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定