Sid*_*tha 0 java function-pointers
我已经看过这里,它适用于包含Runnables的参数减少方法列表.我需要Consumer在我的情况下.这是我到目前为止:
import com.google.common.collect.ImmutableList;
import java.util.List;
import java.util.function.Consumer;
public class experiment {
private static List<Consumer<String>> activities;
public experiment (){
activities = ImmutableList.of(
(userId) -> this::bar, // throws error
(userId) -> this::foo);
}
public void bar(String x) {
System.out.println(x);
}
public void foo(String x) {
System.out.println(x);
}
public static void main(String []args) {
for (int i=0; i<2; i++) {
activities.get(i).accept("activity #" + i);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我看到的错误是void is not a functional interface.
我不明白为什么我会这样做,bar并foo实现Consumer接口的accept方法.有什么东西我在这里俯瞰吗?
我相信你想写ImmutableList.of(this::bar, this::foo)而不是ImmutableList.of((userId) -> this::bar, (userId) -> this::foo).
如果你确实想使用lambdas而不是方法引用,那么你应该写ImmutableList.of((userId) -> this.bar(userId), (userId) -> this.foo(userId)).
| 归档时间: |
|
| 查看次数: |
415 次 |
| 最近记录: |