Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method Reference example in JLS

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)?

like image 705
Misha Avatar asked May 08 '15 20:05

Misha


People also ask

What is a method reference?

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.

What is the use of method reference?

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).

What are we using lambdas and method reference for?

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.


1 Answers

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.

like image 68
Tagir Valeev Avatar answered Oct 19 '22 15:10

Tagir Valeev