Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 lambdas execution

How can I do something like this in Java 8?

boolean x = ((boolean p)->{return p;}).apply(true);

Right now I get the following error:

The target type of this expression must be a functional interface

like image 936
Abdul Rahman Avatar asked Sep 03 '15 19:09

Abdul Rahman


People also ask

Does Java 8 have lambdas?

Lambda Expressions were added in Java 8. A lambda expression is a short block of code which takes in parameters and returns a value. Lambda expressions are similar to methods, but they do not need a name and they can be implemented right in the body of a method.

Which is correct about Java 8 lambda expression?

Q 5 - Which of the following is correct about Java 8 lambda expression? A - Lambda expressions are used primarily to define inline implementation of a functional interface.


1 Answers

As per the JLS section 15.27:

It is a compile-time error if a lambda expression occurs in a program in someplace other than an assignment context (§5.2), an invocation context (§5.3), or a casting context (§5.5).

It is also possible to use a lambda expression in a return statement.

We can then rewrite your example in four different ways:

  • By creating an assignment context:

    Function<Boolean, Boolean> function = p -> p;
    boolean x = function.apply(true);
    
  • By creating an invocation context:

    foobar(p -> p);
    
    private static void foobar(Function<Boolean, Boolean> function) {
        boolean x = function.apply(true);
    }
    
  • By creating a casting context:

    boolean x = ((Function<Boolean, Boolean>) p -> p).apply(true);
    
  • Using a return statement:

    boolean x = function().apply(true);
    
    private static Function<Boolean, Boolean> function() {
        return p -> p;
    }
    

Also, in this simple example, the whole lambda expression can be rewritten as:

UnaryOperator<Boolean> function = UnaryOperator.identity();
like image 192
Tunaki Avatar answered Oct 09 '22 19:10

Tunaki