Java 8 functional interface with no arguments and no return value
Asked Answered
P

4

145

What is the Java 8 functional interface for a method that takes nothing and returns nothing?

I.e., the equivalent to the C# parameterless Action with void return type?

Palaeozoology answered 26/5, 2014 at 11:8 Comment(2)
somewhat surprisingly, even Supplier<Void> won't work since void cannot be converted to Void XDFilefish
I disagree with the use Runnable advice. It miscommunicates intent: https://mcmap.net/q/136591/-java-8-functional-interface-with-no-arguments-and-no-return-valueAntihistamine
C
134

If I understand correctly you want a functional interface with a method void m(). In which case you can simply use a Runnable.

Clemenciaclemency answered 26/5, 2014 at 11:22 Comment(9)
Yes, I was looking for it in the new java.util.functionpackage and I completely forgot the old RunnablePalaeozoology
Runnable's interface specification indicates it is to provide executable code to the Thread class. It doesn't seem right to me to use Runnable where it's not intended for execution by a thread; seems misleading. Runnable is defined as a FunctionalInterface because it meets the specification of a functional interface and can be created using lambda syntax. Why not create your own functional interface? see Runnable, see FunctionalInterfaceTergum
@Tergum (i) Runnable is annotated with @FunctionalInterface and (ii) even in the context of a lambda expression it will be executed on a thread: the thread in which the lambda is run which may be the current thread...Clemenciaclemency
I agree with @TheSecretSquad, while it satisfies the functional requirement, it does not sound very semantic, Runnable is commonly associated with creating threads. A simple Worker functional interface with a doWork method would have been nice. EDIT: Oops: #27973794Dravidian
Fleshing out @jpangamarca's "Oops" above: In the comments on the duplicate question he linked, Brian Goetz confirmed that Runnable was intended to be used for this purpose, not just for threading contexts.Bellamy
Given that that's the case, though, I think the javadoc should be made more generic: docs.oracle.com/javase/8/docs/api/java/lang/Runnable.htmlBellamy
If you end up writing lambdas without parameters and return values, you are likely to write code with side effects. So it's time to think over and change your design.Sandblind
FWIW Java 11 standard library uses a Runnable for this purpose in at least one place: Optional::ifPresentOrElse (Which admittedly also made me think at first if it would run on a different thread)Tamah
since Java 19, it's actually the official way: see docs.oracle.com/en/java/javase/19/docs/api/java.base/java/lang/… vs Java 18's docs.oracle.com/en/java/javase/18/docs/api/java.base/java/lang/…Filefish
M
34

Just make your own

@FunctionalInterface
public interface Procedure {
    void run();

    default Procedure andThen(Procedure after){
        return () -> {
            this.run();
            after.run();
        };
    }

    default Procedure compose(Procedure before){
        return () -> {
            before.run();
            this.run();
        };
    }
}

and use it like this

public static void main(String[] args){
    Procedure procedure1 = () -> System.out.print("Hello");
    Procedure procedure2 = () -> System.out.print("World");

    procedure1.andThen(procedure2).run();
    System.out.println();
    procedure1.compose(procedure2).run();

}

and the output

HelloWorld
WorldHello
Mcgriff answered 31/7, 2017 at 15:7 Comment(1)
since Java 19, no need to make your own, Runnable is the officially documented answer.Filefish
A
2

Note: For a more complete solution, here's an StackOverflow Answer I've posted.


I don't like the decision made by the Java library team to leave out the case of a no-parameter-no-return-value Function interface, and nudging those who need one to use Runnable. I think it inaccurately, and even incorrectly, redirects attention and subsequent assumptions when trying to read through a code base. Especially years after the original code was written.

Given communication and readability are far higher concerns for me and my audiences, I have composed a small helper interface designed and named in the spirit of the Java library's missing case:

@FunctionalInterface
public interface VoidSupplier {
  void get();
}

And in my case, the likelihood of an Exception being thrown in the method is considerably higher, so I actually added a checked exception like this:

@FunctionalInterface
public interface VoidSupplier {
  void get() throws Exception;
}
Antihistamine answered 21/7, 2023 at 22:46 Comment(0)
A
1

@FunctionalInterface allows only method abstract method Hence you can instantiate that interface with lambda expression as below and you can access the interface members

        @FunctionalInterface
        interface Hai {
        
            void m2();
        
            static void m1() {
                System.out.println("i m1 method:::");
            }
        
            default void log(String str) {
                System.out.println("i am log method:::" + str);
            }
        
        }
    
    public class Hello {
        public static void main(String[] args) {
    
            Hai hai = () -> {};
            hai.log("lets do it.");
            Hai.m1();
    
        }
    }

output:

i am log method:::lets do it.
i m1 method:::
Accroach answered 19/5, 2020 at 5:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.