I have a class for walking a directory tree and performing an action on each file/directory. It looks like this:
class DirWalker {
public static void walkDirs(Path startingPath, Consumer<Path> vAction) {...}
}
In another class I have the following:
public static Consumer<Path> doVisit = p -> {...}
I tried to use this in my Java code like this:
DirWalker.walkDirs(/* a path */, MyClass::doVisit);
However, I get an error here saying that 'MyClass does not define doVisit(Path) that is applicable here'. I can change the doVisit member to a method and it works.
If I were to use a lambda inline in the walkDirs call it would work fine. But creating an instance of a Consumer and passing that to the walkDirs method fails. Why is this the case?
You would use the method reference syntax (
MyClass::doVisit) only if doVisit was a method. As you're declaring it, doVisit is a field, and should be accessed asMyClass.doVisitIf you want to use the method reference syntax, you can write it as a method that satisfies the
Consumer<Path>interface instead of an inline lambda expression, like below