Juan Manuel
Juan Manuel

Reputation: 123

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.

Upvotes: 9

Views: 162

Answers (2)

sepp2k
sepp2k

Reputation: 370367

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.

Upvotes: 10

Juan Manuel
Juan Manuel

Reputation: 123

Thanks Stuart for the answer:

java.lang.Runnable a = () -> {};

Now that you stated it, it seems perfectly obvious...

Upvotes: 1

Related Questions