10

ラムダ式が一部の機能インターフェイスに割り当て可能で、他の機能インターフェイスには割り当てられない理由を理解するのに苦労しています。Metrics ライブラリの機能的なインターフェースを使用した例:

Gauge<Double> foo = () -> { return null; };
RatioGauge bar = () -> { return null; };

2 番目のステートメントにはコンパイル エラーがあります (Eclipse の場合)。

この式の対象の型は関数型インターフェイスでなければなりません

私が知る限り、RationGauge は機能的なインターフェースです。何か不足していますか?

4

2 に答える 2

24

An abstract class (even if it only has one abstract method) is not a functional interface. Only an interface can be one.

From JLS 9.8:

A functional interface is an interface that has just one abstract method (aside from the methods of Object)... (emphasis added)

The original idea was to let abstact classes be expressed as a lambda; they were called "SAM types," which stood for "single abstract method." That turned out to be a difficult problem to solve efficiently. This thread talks a bit about why; basically, the base class's constructor made it difficult.

于 2014-04-01T19:04:34.630 に答える