Is there a method reference way to express a (Runnable) lambda that does nothing?

GhostCat salutes Monica C. :

I have an AutoCloseable class that executes a Runnable within close(), like this:

static class Whatever implements AutoCloseable {
    Runnable r;
    public Whatever(Runnable r) {
        this.r = r;
    }

    @Override
    public void close() throws Exception {
        r.run();
    }
}

@Test
public void testAutoClose() throws Exception {
    List<Boolean> updateMe = Arrays.asList(false);
    AutoCloseable ac = new Whatever(() -> updateMe.set(0, true));
    ac.close();
    assertThat("close() failed to update list", updateMe, is(Collections.singletonList(true)));
}

The above works nicely. And enables me to have code like

new Whatever( () -> foo() );

to do "something".

But: there is one case, where, well nothing should happen for close(). This works:

new Whatever( () -> {} ); 

As said, that does the job, yet I am wondering: is there a way to express that "empty Runnable" in any other way, for example using some sort of method reference?

Andrew Tobilko :

Option 1

I would overload the constructor with a no-arg version.

public Whatever() {
    this(() -> {}); 
}

() -> {} looks consice and self-explanatory to me.

Option 2

As an alternative, you could go with a utility class that defines an empty Runnable method

public final class EmptyUtils {
    public static Runnable emptyRunnable() { return () -> {}; }
}

which you could statically import

new Whatever(emptyRunnable());

Option 3

I find this option particularly interesting (and you asked for a method reference)

new Whatever(EmptyRunnable::get);

even though it requires to write a (completely) dummy class

class EmptyRunnable {
    public static void get() {}
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=140280&siteId=1