我很难分类为什么lambda表达式可以分配给一些功能接口,而不是其他功能接口.一个例子,使用一些功能界面从
Metrics library:
Gauge<Double> foo = () -> { return null; }; RatioGauge bar = () -> { return null; };
第二个语句有一个编译错误(在Eclipse中):
The target type of this expression must be a functional interface
据我所知,RatioGauge is a functional interface.我错过了什么吗?
解决方法
一个抽象类(即使它只有一个抽象方法)不是一个功能界面.只有一个接口可以是一个.
从JLS 9.8:
A functional interface is an interface that has just one abstract method (aside from the methods of Object)… (emphasis added)
最初的想法是让abstact类被表达为lambda;它们被称为“SAM类型”,它代表“单抽象方法”.这是一个难以解决的问题. This thread谈谈为什么;基本上,基类的构造函数使得它变得困难.