0

I try to make create multi dirs and files more easier with follwoing code:

package ro.ex;

class File {

    public interface Lamb {
        public void call(Class c);
    }

    public static void tap(Lamb l) {
        l.call(File.class);
    }

    public static void mkdir(String path) {
    }

    public static void main(String[] args) {
        File.tap((f) -> {
            f.mkdir("dir");
            f.mkdir("dir2");
        });
    }
}

but in f.mkdir("dir"), intellij idea raise can't resolve method 'mkdir'

my question is: how to change code to make code in main block work well

1
  • Why do your mkdir calls all pass a String but your mkdir method doesn't take any parameters? Commented Nov 10, 2014 at 22:56

2 Answers 2

3

According to the method contract, File.tap() accepts a Lamb parameter.

Lamb is a functional interface (contains only one abstract method) and the body of your lambda is the anonymous implementation of its abstract method.

The abstract method has a definition public void call(Class c) and this is why your code fails to compile. You're trying to pass a File object, instead of a Class one.

In the mean time, mkdir is a static method and can be invoked like this:

public static void main(String[] args) {
    File.tap((f) -> {
        File.mkdir("dir");
        File.mkdir("dir2");
    });
}
Sign up to request clarification or add additional context in comments.

2 Comments

How to change "Class" to "File.class", i try "File.class" but syntax is wrong
Just make it: public void call(File f);
1

You defined a (functional) interface Lamb whose single method takes a Class as an argument.

So the f in your lambda expression (f) -> { ... } is of type Class. But this class does not know the method mkdir.

You have a static method mkdir in your custom class File. Static methods are called like this:

File.tap((f) -> {
    File.mkdir("dir");
    File.mkdir("dir2");
});

This makes the Class argument in method Lamb.call(Class) rather useless. Maybe you want to reconsider the design.

2 Comments

How to change "Class" to "File.class", i try "File.class" but syntax is wrong
If you want to call a file, simply declare your method: void call(File f) and make sure to not mix it up with java.io.File.

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.