0

I am trying to get IZO-809 certification I was reading the OCA/OCP SE8 test book and a code really caught my attention.

The code gets me to this question.

I know consumer get a parameter and not return nothing and Supplier has not parameters and returns a value.

But this code is almost the same after the ->.

public class Pregunta24{
   private final Object obj;
   public Pregunta24(final Object obj){
      this.obj = obj;
   }    
}
//Returns a Supplier
private final Supplier<Pregunta24>supplier = ()->new Pregunta24("HI");
//Returns a Consumer.
private final Consumer<Pregunta24>consumer = a->new Pregunta24(a);

Both codes work.

But if this code not work i know that consumer doesn't return nothing.

private final Consumer<String>consumerString = String::length

I know this not work because consumer doesn't return a value my question is in the supplier code and the consumer code the code is right after the -> mark but this time is considered return in fact a instance of the class.

My question is why sometimes Java complaints that is a return value and something not?

I mean this code.

private final Supplier<Pregunta24>supplier = ()->new Pregunta24("HI");
// I would think is returning a instance of the Pregunta24 class.
private final Consumer<Pregunts24>consumer = a->new Pregunta24(a);

Is returning the same after the -> but why in the consumer don't say the error.

incompatible types: bad return type in lambda expression

But if do this I do

final Consumer<String>consumerString = a->1;

I think the code after the -> is context inferred.

halfer
  • 19,824
  • 17
  • 99
  • 186
chiperortiz
  • 4,751
  • 9
  • 45
  • 79

1 Answers1

3

According to javadoc Consumer:

Represents an operation that accepts a single input argument and returns no result.

Consumer<Pregunts24>consumer = a->new Pregunta24(a);

doesn't actually return anything. This basically is implementation of Consumer#accept method, which accepts an object of type T and has void as return type.

public void accept(Pregunta24 a) {
    new Pregunta24(a);
}

You are not returning anything. Same thing with

Consumer<String>consumerString = String::length
public void accept(String a) {
    a.length();
}

However

Consumer<String>consumerString = a->1;

is an invalid expression which is translated to something like this:

 public void accept(String a) {
        1;
 }
Anton Balaniuc
  • 10,889
  • 1
  • 35
  • 53
  • But why the implementation of the consumerSring a->1 is a compiler error if in the accept is not returning nothing neither? – chiperortiz Jun 01 '18 at 20:47
  • 1
    @chiperortiz, because java language specification doesn't recognize `1;` as a valid expression. Please see https://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.8. Try to declare `public class Main { public static void main(String[] args) { 1; } }` and you will see the same error, it is not about `Consumer`, but Java lang spec instead. – Anton Balaniuc Jun 02 '18 at 11:04