java 8 - Return method reference -
i playing around in java 8. how can return method reference?
i able return lambda not method reference.
my attempts:
public supplier<?> foreachchild(){ return new arraylist<?>::foreach; }
or
public function<?> foreachchild(){ return new arraylist<?>::foreach; }
you have small mis-understanding of how method-references work.
first of all, cannot new
method-reference.
then, let's reason through want do. want method foreachchild
able return accept list
, consumer
. list
on object invoke foreach
on, , consumer
action perform on each element of list. that, can use biconsumer
: represents operation taking 2 parameters , returning no results: first parameter list , second parameter consumer.
as such, following work:
public <t> biconsumer<list<t>, consumer<? super t>> foreachchild() { return list::foreach; }
this type of method-reference called "reference instance method of arbitrary object of particular type". happens first parameter of type list<t>
becomes object on foreach
invoked, giving parameter consumer
.
then can use like:
foreachchild().accept(arrays.aslist("1", "2"), system.out::println);
Comments
Post a Comment