2017-12-16 27 views
0

私はこのような方法を持っています。今メソッド参照がこれで動作しないのはなぜですか?

static <R> R applyOthers(Some some, Function<List<Other>, R> function) { 
    List<Other> others = ...; 
    return function.appply(others); 
} 

私はこれを試してみてください、

withSome(some -> { 
    List<Other> others1 = applyOthers(some, v -> v); // works 
    List<Other> others2 = applyOthers(some, Function::identity); // doesn't 
}); 

エラー、私が得ます。

incompatible types: unexpected static method <T>identity() found in unbound lookup 
    where T is a type variable: 
    T extends Object declared in method <T>identity() 

なぜ::identityが機能しないのですか?

答えて

2
Function<Object, Object> f1 = v1 -> v1; 
Supplier<Object> s1 = Function::identity; 
Supplier<Object> s2 =() -> Function.identity(); 

このコードを参照すると、ここでメソッドリファレンスを誤って使用していると思います。 SomeObject::methodと言うとき、このメソッド参照はある種の機能インタフェースと一致するはずです。上記の例では、Function::identityは、java.util.function.Functionインスタンスではなく、サプライヤインスタンスの一種です。

+0

これは、メイトです! 'Function :: identity'ではなく、' Function.identity() 'でなければなりません。ありがとう。 –

関連する問題