JLS 15.13 lists examples of method reference expressions. One of them is
(test ? list.replaceAll(String::trim) : list) :: iterator
which doesn't make sense since replaceAll
is void
. Am I misunderstanding something or is this an error in JLS (perhaps an earlier version of replaceAll
returned the resulting list)?
Method references are a special type of lambda expressions. They're often used to create simple lambda expressions by referencing existing methods. There are four kinds of method references: Static methods. Instance methods of particular objects. Instance methods of an arbitrary object of a particular type.
A method reference is an alternative to creating an instance of a reference type. Among several other uses, method references can be used to create a functional interface instance (that is, an instance of a functional interface type).
Method reference is used to refer method of functional interface. It is compact and easy form of lambda expression. Each time when you are using lambda expression to just referring a method, you can replace your lambda expression with method reference.
Well, technically it's not specified in JLS that the list
variable has java.util.List
type. So this code can be compiled with some custom type:
public static class MyList implements Iterable<String> {
private final List<String> list = new ArrayList<>();
public MyList add(String val) {
list.add(val);
return this;
}
public MyList replaceAll(UnaryOperator<String> op) {
list.replaceAll(op);
return this;
}
public Iterator<String> iterator() {
return list.iterator();
}
}
public Supplier<Iterator<String>> it(MyList list, boolean test) {
return (test ? list.replaceAll(String::trim) : list) :: iterator;
}
But in general it looks like they intended to make an example based on java.util.List
. Thus probably it would be best to replace it with something JDK-based.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With