15

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

Tunaki
  • 132,869
  • 46
  • 340
  • 423
Abdul Rahman
  • 1,294
  • 22
  • 41
  • The examples I can see do not use {}, since it is meant to be a single statement. [Tutorial](http://winterbe.com/posts/2014/03/16/java-8-tutorial/) – flaschenpost Sep 03 '15 at 19:24
  • Same thing without a {} around return p. I dont think so that is the problem. – Abdul Rahman Sep 03 '15 at 19:32
  • 2
    Your mistake is in assuming that `Function` has any special status so that the lambda's type would be automatically coerced into it. Your expression has in fact no target type constraint. – Marko Topolnik Sep 03 '15 at 19:49
  • You can fix the code by telling the compiler the type for the lambda: boolean x = ((Function) p->p).apply(true); – Matthias Wimmer Sep 06 '15 at 17:21

1 Answers1

28

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();
Tunaki
  • 132,869
  • 46
  • 340
  • 423