Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the type of '()->{}' in Java 8?

In Java8, what is the type of the following lambda ???

() -> {}

That is a function that takes no arguments and returns nothing.

Stated differently:

public class A {
  static void a(){}
  static void main(String[] args) {
    ???? a = A::a
  }
}

What should I replace the question marks with?

In Scala, this would be a Function0[Unit] I think, but I don't find anything alike in Java.

like image 545
Juan Manuel Avatar asked Mar 24 '15 15:03

Juan Manuel


1 Answers

Unlike Scala, lambdas in Java don't have a fixed type. Rather they take the type of whichever interface you declare the variable as, as long as that interface defines exactly one abstract method and that method has the same signature as the lambda.

So in your case, you want an interface that defines a void method that takes no parameters. Runnable would be one example of that.

like image 198
sepp2k Avatar answered Nov 09 '22 23:11

sepp2k