2

I really need some help. This is my functional interface:

/**
 * This class represents a filter.
 */
@FunctionalInterface
interface FileFilter {
    /**
     * This method gets a file path and filters it in some method.
     * @return a list of the remaining files after this filter.
     * @throws IOException
     */
    abstract boolean filter(Path path) throws IOException;
}

This is the lambda function that I've written:

    static FileFilter modeFilter(String value, boolean containsNo, Predicate<Path> pathMethod)
    throws IOException{
        if (value.equals(YES)) {
            if (containsNo) {
                return path -> !pathMethod.test(path);
            } else {
                return path -> pathMethod.test(path);
            }
        }

        if (containsNo) {
            return path -> pathMethod.test(path);
        }
        return path -> !pathMethod.test(path);
    }

I am giving the filter this parameters:

Filters.modeFilter(commandParts[1], containsNOT, x -> Files.isHidden(x))

The problem is that I get a compliation error in Files.isHidden that says that there is an Excpetion not handled - IOExeption.

I made sure that the method that calls modeFilter throws IOExeption, so this is not the problem. How do I solve this?

Thank you.

1 Answer 1

3

Your method takes a Predicate<Path> as argument.

The signature of the Predicate function is

boolean test(T)

But the signature of Files.isHidden is

boolean isHidden(Path path) throws IOException

So they don't match: a predicate is not supposed to throw an IOException, but Files.isHidden() can.

Solution: pass a FileFilter as argument, rather than a Predicate<File>, since the only reason FileFilter exists is precisely so that it can throw an IOException, unlike a Predicate.

Note that the modeFilter method has no reason to throw an IOException: all it does is creating a FileFilter. It never calls it. So it can't possibly throw an IOException.

Sign up to request clarification or add additional context in comments.

2 Comments

I need to create a FileFilter according to these conditions.. So how do I modify the passed FileFilter to the different options? How do I create a new lambda based on the given one?
Replace Predicate<Path> pathMethod by FileFilter pathMethod. And replace pathMethod.test(path) by pathMethod.filter(path).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.