L
L
Longes2012-07-19 09:10:55
Java
Longes, 2012-07-19 09:10:55

How to implement higher order functions in Java?

I have a class, most of the methods differ only by calling different functions at the same point:

public MatrixDto getContent (...) {
...
        final List<Content> list = <b>contentDao.x(a, b);</b>
...
        return matrixDto;
}

In this example, this is the contentDao.x(a,b) function. I want to replace all these functions with a single higher order function that could take the desired function as input, and substitute it in place of contentDao.x (). Can this be done somehow in Java?
Note: I cannot change the implementation of the x() function, since it is a MyBatis interface

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
apangin, 2012-07-19
@apangin

Through interfaces, such as Callable .

public MatrixDto getContent(Callable<List<Content>> function) {
    ...
    final List<Content> list = function.call();
    ...
}

// а вызывать так:
getContent(new Callable<List<Content>>() {
    public List<Content> call() { return contentDao.x(a, b); }
});

O
Ololesha Ololoev, 2012-07-20
@alexeygrigorev

Have a look at Google Guava docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Function.html
Although I increasingly think that higher-order functions in Java will not lead to anything good, they will only clutter code due to the verbosity of the language. Almost always, imperative code in Java looks better and more understandable than the so-called. "functional".
Try to compare and you will understand. A mess of anonymous classes is not the best code to read and understand.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question