Return method reference

北城余情 提交于 2019-12-01 12:07:27

You have a small mis-understanding of how method-references work.

First of all, you cannot new a method-reference.

Then, let's reason through what you want to do. You want the method forEachChild to be able to return something that would accept a List and a Consumer. The List would be on which object to invoke forEach on, and the Consumer would be the action to perform on each element of the list. For that, you can use a BiConsumer: this represents an operation taking 2 parameters and returning no results: the first parameter is a list and the second parameter is a consumer.

As such, the following will work:

public <T> BiConsumer<List<T>, Consumer<? super T>> forEachChild() {
    return List::forEach;
}

This type of method-reference is called "Reference to an instance method of an arbitrary object of a particular type". What happens is that the first parameter of type List<T> becomes the object on which forEach will be invoked, by giving it as parameter the Consumer.

Then you can use it like:

forEachChild().accept(Arrays.asList("1", "2"), System.out::println);

I would like to add some points.

You can't instantiate unbounded type instance.

List<?> list = new ArrayList<?>();

Second, as Tunaki mentioned, you can't make references to new MyObject::staticMethod when you make method references

The other thing is, forEach(Consumer<T> consumer) (Terminal operation for pipeline streams) doesn't return anything. It only eats whatever we feed it.

-Hope this may help :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!