Why does .forEach(val -> list.add()) compile whereas .forEach(val -> true) doesn't?











up vote
6
down vote

favorite












It's better to express this behavior in the code:



List<Integer> list= new ArrayList<>();
Stream.of(1,2,3).forEach(i -> list.add(1)); // COMPILES

Stream.of(1,2,3).forEach(i -> true); // DOES NOT COMPILE!


forEach(...) accepts Consumer, but why does the first example compile if List interface has following signature boolean add(E e)?










share|improve this question
























  • What are you trying to achieve with the second statement?
    – Nicholas K
    3 hours ago










  • Hint: Stream.of(1,2,3).forEach(i -> {return list.add(1);}) also doesn't compile. Hint2: What method ( X -> Y mapping) Consumer<T> represents (take a look at abstract method it contains, what type of parameter(s) it accepts and what is its return type)?
    – Pshemo
    3 hours ago












  • Instead of simply stating "does not compile", it would be much better if you could show the precise error message you are getting. In particular, at least one answer is operating under the assumption that you are getting a syntax error (although in that case, "does not parse" would be more correct than "does not compile"), but I don't think a syntax error is the problem.
    – Jörg W Mittag
    3 hours ago










  • @JörgWMittag The compilation error prints incompatible types: bad return type in lambda expression missing return value. @Pshemo before I started this thread I checked what is the signature is. Consumer.accept(T t) should return void (docs.oracle.com/javase/8/docs/api/java/util/function/…)
    – Leonid Dashko
    27 mins ago

















up vote
6
down vote

favorite












It's better to express this behavior in the code:



List<Integer> list= new ArrayList<>();
Stream.of(1,2,3).forEach(i -> list.add(1)); // COMPILES

Stream.of(1,2,3).forEach(i -> true); // DOES NOT COMPILE!


forEach(...) accepts Consumer, but why does the first example compile if List interface has following signature boolean add(E e)?










share|improve this question
























  • What are you trying to achieve with the second statement?
    – Nicholas K
    3 hours ago










  • Hint: Stream.of(1,2,3).forEach(i -> {return list.add(1);}) also doesn't compile. Hint2: What method ( X -> Y mapping) Consumer<T> represents (take a look at abstract method it contains, what type of parameter(s) it accepts and what is its return type)?
    – Pshemo
    3 hours ago












  • Instead of simply stating "does not compile", it would be much better if you could show the precise error message you are getting. In particular, at least one answer is operating under the assumption that you are getting a syntax error (although in that case, "does not parse" would be more correct than "does not compile"), but I don't think a syntax error is the problem.
    – Jörg W Mittag
    3 hours ago










  • @JörgWMittag The compilation error prints incompatible types: bad return type in lambda expression missing return value. @Pshemo before I started this thread I checked what is the signature is. Consumer.accept(T t) should return void (docs.oracle.com/javase/8/docs/api/java/util/function/…)
    – Leonid Dashko
    27 mins ago















up vote
6
down vote

favorite









up vote
6
down vote

favorite











It's better to express this behavior in the code:



List<Integer> list= new ArrayList<>();
Stream.of(1,2,3).forEach(i -> list.add(1)); // COMPILES

Stream.of(1,2,3).forEach(i -> true); // DOES NOT COMPILE!


forEach(...) accepts Consumer, but why does the first example compile if List interface has following signature boolean add(E e)?










share|improve this question















It's better to express this behavior in the code:



List<Integer> list= new ArrayList<>();
Stream.of(1,2,3).forEach(i -> list.add(1)); // COMPILES

Stream.of(1,2,3).forEach(i -> true); // DOES NOT COMPILE!


forEach(...) accepts Consumer, but why does the first example compile if List interface has following signature boolean add(E e)?







java java-8 compiler-errors java-stream






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 3 hours ago









Nicholas K

4,95141031




4,95141031










asked 3 hours ago









Leonid Dashko

65069




65069












  • What are you trying to achieve with the second statement?
    – Nicholas K
    3 hours ago










  • Hint: Stream.of(1,2,3).forEach(i -> {return list.add(1);}) also doesn't compile. Hint2: What method ( X -> Y mapping) Consumer<T> represents (take a look at abstract method it contains, what type of parameter(s) it accepts and what is its return type)?
    – Pshemo
    3 hours ago












  • Instead of simply stating "does not compile", it would be much better if you could show the precise error message you are getting. In particular, at least one answer is operating under the assumption that you are getting a syntax error (although in that case, "does not parse" would be more correct than "does not compile"), but I don't think a syntax error is the problem.
    – Jörg W Mittag
    3 hours ago










  • @JörgWMittag The compilation error prints incompatible types: bad return type in lambda expression missing return value. @Pshemo before I started this thread I checked what is the signature is. Consumer.accept(T t) should return void (docs.oracle.com/javase/8/docs/api/java/util/function/…)
    – Leonid Dashko
    27 mins ago




















  • What are you trying to achieve with the second statement?
    – Nicholas K
    3 hours ago










  • Hint: Stream.of(1,2,3).forEach(i -> {return list.add(1);}) also doesn't compile. Hint2: What method ( X -> Y mapping) Consumer<T> represents (take a look at abstract method it contains, what type of parameter(s) it accepts and what is its return type)?
    – Pshemo
    3 hours ago












  • Instead of simply stating "does not compile", it would be much better if you could show the precise error message you are getting. In particular, at least one answer is operating under the assumption that you are getting a syntax error (although in that case, "does not parse" would be more correct than "does not compile"), but I don't think a syntax error is the problem.
    – Jörg W Mittag
    3 hours ago










  • @JörgWMittag The compilation error prints incompatible types: bad return type in lambda expression missing return value. @Pshemo before I started this thread I checked what is the signature is. Consumer.accept(T t) should return void (docs.oracle.com/javase/8/docs/api/java/util/function/…)
    – Leonid Dashko
    27 mins ago


















What are you trying to achieve with the second statement?
– Nicholas K
3 hours ago




What are you trying to achieve with the second statement?
– Nicholas K
3 hours ago












Hint: Stream.of(1,2,3).forEach(i -> {return list.add(1);}) also doesn't compile. Hint2: What method ( X -> Y mapping) Consumer<T> represents (take a look at abstract method it contains, what type of parameter(s) it accepts and what is its return type)?
– Pshemo
3 hours ago






Hint: Stream.of(1,2,3).forEach(i -> {return list.add(1);}) also doesn't compile. Hint2: What method ( X -> Y mapping) Consumer<T> represents (take a look at abstract method it contains, what type of parameter(s) it accepts and what is its return type)?
– Pshemo
3 hours ago














Instead of simply stating "does not compile", it would be much better if you could show the precise error message you are getting. In particular, at least one answer is operating under the assumption that you are getting a syntax error (although in that case, "does not parse" would be more correct than "does not compile"), but I don't think a syntax error is the problem.
– Jörg W Mittag
3 hours ago




Instead of simply stating "does not compile", it would be much better if you could show the precise error message you are getting. In particular, at least one answer is operating under the assumption that you are getting a syntax error (although in that case, "does not parse" would be more correct than "does not compile"), but I don't think a syntax error is the problem.
– Jörg W Mittag
3 hours ago












@JörgWMittag The compilation error prints incompatible types: bad return type in lambda expression missing return value. @Pshemo before I started this thread I checked what is the signature is. Consumer.accept(T t) should return void (docs.oracle.com/javase/8/docs/api/java/util/function/…)
– Leonid Dashko
27 mins ago






@JörgWMittag The compilation error prints incompatible types: bad return type in lambda expression missing return value. @Pshemo before I started this thread I checked what is the signature is. Consumer.accept(T t) should return void (docs.oracle.com/javase/8/docs/api/java/util/function/…)
– Leonid Dashko
27 mins ago














4 Answers
4






active

oldest

votes

















up vote
7
down vote













Though you might be looking just for



Stream.of(1,2,3).forEach(list::add); // adding all to `list`



why does the first example compile if List interface has following
signature boolean add(E e)




Primarily because the return type of the method is ignored in the first call. This is what it expands to:



Stream.of(1,2,3).forEach(new Consumer<Integer>() {
@Override
public void accept(Integer i) {
list.add(1); // ignored return type
}
}); // COMPILES


On the other hand, the other lambda representation is more like a Predicate(which is also a FunctionalInterface) represented as returning true always from its test method. If you even try to represent it as a Consumer, it might just look like



Stream.of(1,2,3).forEach(new Consumer<Integer>() {
@Override
public void accept(Integer i) {
return true; // you can correlate easily now why this wouldn't compile
}
}); // DOES NOT COMPILE!





share|improve this answer






























    up vote
    1
    down vote













    The Special Void-Compatibility Rule (JLS) says that a lambda that returns void may accept a statement whose return is non-void. In this case, the return is discarded. hence this compiles.



    Stream.of(1,2,3).forEach(i -> list.add(1)); // return value of add is ignored


    To word it a bit differently by quoting Java-8 in Action book:




    If a lambda has a statement expression as its body, it’s compatible
    with a function descriptor that returns void (provided the parameter
    list is compatible too). For example, both of the following lines are
    legal even though the method add of a List returns a boolean and not
    void as expected in the Consumer context (T -> void):




    // Predicate has a boolean return
    Predicate<String> p = s -> list.add(s);
    // Consumer has a void return
    Consumer<String> b = s -> list.add(s);


    As for the second example, this is explicitly trying to return a boolean where it's not expected hence not possible.



    Stream.of(1,2,3).forEach(i -> true);  


    in other words:



    Stream.of(1,2,3).forEach(i -> {return true;});


    As you already know forEach takes a Consumer so attempting to "explicitly" return a boolean should & will yield a compilation error.






    share|improve this answer























    • I believe that this is the answer, but I am still having trouble seeing it clearly. The lambda spec explicitly distinguishes between lambdas with expression bodies and lambdas with block bodies, whereas void-compatibility rule talks specifically about lambdas with a block body and does not mention expression-bodied lambdas. However, both examples in the question are expression-bodies lambdas. I cannot point my finger on exactly that part of the spec that says this. Your quote from Java in Action seems to interpret the spec the same way as you, and I believe that interpretation is correct, I …
      – Jörg W Mittag
      2 hours ago










    • … just can't find where it is actually supported by the spec.
      – Jörg W Mittag
      2 hours ago


















    up vote
    0
    down vote













    forEach() as a Consumer as the one and only parameter therefore you need to give an implemention of the method accept() which returns void so on the second example you're implementing a method with the given assinature static boolean method(int).






    share|improve this answer

















    • 3




      Can you explain, why list.add(1), an expression that evaluates to true is a correct implementation of a Consumer, whereas true, an expression that evaluates to true, is an incorrect implementation?
      – Jörg W Mittag
      3 hours ago










    • Like other people said before if you expand the lambda with the { } you'll get an expression on first case and an invalid statement at second.
      – chriptus13
      2 hours ago










    • If you expand the lambda with braces, you get a syntax error for the second example, which is however not what the OP is getting. He is getting a type error, which is something completely different.
      – Jörg W Mittag
      2 hours ago






    • 2




      As was pointed out in another answer, the reason is void-compatibility, not syntax.
      – Jörg W Mittag
      2 hours ago










    • If you don't use the brackets it either is a value which gets translated to a return or a method call.
      – chriptus13
      2 hours ago


















    up vote
    -2
    down vote













    forEach(Consumer<? super T> action) is asking for an action (some process to be done with the element). It needs a method name, not a variable. The return type of the given method doesn't matter.




    Performs an action for each element of this stream.



    ...



    Parameters




    • action - a non-interfering action to perform on the
      elements


    Stream (Java Platform SE 8)







    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53794839%2fwhy-does-foreachval-list-add-compile-whereas-foreachval-true-doesn%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      4 Answers
      4






      active

      oldest

      votes








      4 Answers
      4






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      7
      down vote













      Though you might be looking just for



      Stream.of(1,2,3).forEach(list::add); // adding all to `list`



      why does the first example compile if List interface has following
      signature boolean add(E e)




      Primarily because the return type of the method is ignored in the first call. This is what it expands to:



      Stream.of(1,2,3).forEach(new Consumer<Integer>() {
      @Override
      public void accept(Integer i) {
      list.add(1); // ignored return type
      }
      }); // COMPILES


      On the other hand, the other lambda representation is more like a Predicate(which is also a FunctionalInterface) represented as returning true always from its test method. If you even try to represent it as a Consumer, it might just look like



      Stream.of(1,2,3).forEach(new Consumer<Integer>() {
      @Override
      public void accept(Integer i) {
      return true; // you can correlate easily now why this wouldn't compile
      }
      }); // DOES NOT COMPILE!





      share|improve this answer



























        up vote
        7
        down vote













        Though you might be looking just for



        Stream.of(1,2,3).forEach(list::add); // adding all to `list`



        why does the first example compile if List interface has following
        signature boolean add(E e)




        Primarily because the return type of the method is ignored in the first call. This is what it expands to:



        Stream.of(1,2,3).forEach(new Consumer<Integer>() {
        @Override
        public void accept(Integer i) {
        list.add(1); // ignored return type
        }
        }); // COMPILES


        On the other hand, the other lambda representation is more like a Predicate(which is also a FunctionalInterface) represented as returning true always from its test method. If you even try to represent it as a Consumer, it might just look like



        Stream.of(1,2,3).forEach(new Consumer<Integer>() {
        @Override
        public void accept(Integer i) {
        return true; // you can correlate easily now why this wouldn't compile
        }
        }); // DOES NOT COMPILE!





        share|improve this answer

























          up vote
          7
          down vote










          up vote
          7
          down vote









          Though you might be looking just for



          Stream.of(1,2,3).forEach(list::add); // adding all to `list`



          why does the first example compile if List interface has following
          signature boolean add(E e)




          Primarily because the return type of the method is ignored in the first call. This is what it expands to:



          Stream.of(1,2,3).forEach(new Consumer<Integer>() {
          @Override
          public void accept(Integer i) {
          list.add(1); // ignored return type
          }
          }); // COMPILES


          On the other hand, the other lambda representation is more like a Predicate(which is also a FunctionalInterface) represented as returning true always from its test method. If you even try to represent it as a Consumer, it might just look like



          Stream.of(1,2,3).forEach(new Consumer<Integer>() {
          @Override
          public void accept(Integer i) {
          return true; // you can correlate easily now why this wouldn't compile
          }
          }); // DOES NOT COMPILE!





          share|improve this answer














          Though you might be looking just for



          Stream.of(1,2,3).forEach(list::add); // adding all to `list`



          why does the first example compile if List interface has following
          signature boolean add(E e)




          Primarily because the return type of the method is ignored in the first call. This is what it expands to:



          Stream.of(1,2,3).forEach(new Consumer<Integer>() {
          @Override
          public void accept(Integer i) {
          list.add(1); // ignored return type
          }
          }); // COMPILES


          On the other hand, the other lambda representation is more like a Predicate(which is also a FunctionalInterface) represented as returning true always from its test method. If you even try to represent it as a Consumer, it might just look like



          Stream.of(1,2,3).forEach(new Consumer<Integer>() {
          @Override
          public void accept(Integer i) {
          return true; // you can correlate easily now why this wouldn't compile
          }
          }); // DOES NOT COMPILE!






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited 3 hours ago

























          answered 3 hours ago









          nullpointer

          38.5k1073146




          38.5k1073146
























              up vote
              1
              down vote













              The Special Void-Compatibility Rule (JLS) says that a lambda that returns void may accept a statement whose return is non-void. In this case, the return is discarded. hence this compiles.



              Stream.of(1,2,3).forEach(i -> list.add(1)); // return value of add is ignored


              To word it a bit differently by quoting Java-8 in Action book:




              If a lambda has a statement expression as its body, it’s compatible
              with a function descriptor that returns void (provided the parameter
              list is compatible too). For example, both of the following lines are
              legal even though the method add of a List returns a boolean and not
              void as expected in the Consumer context (T -> void):




              // Predicate has a boolean return
              Predicate<String> p = s -> list.add(s);
              // Consumer has a void return
              Consumer<String> b = s -> list.add(s);


              As for the second example, this is explicitly trying to return a boolean where it's not expected hence not possible.



              Stream.of(1,2,3).forEach(i -> true);  


              in other words:



              Stream.of(1,2,3).forEach(i -> {return true;});


              As you already know forEach takes a Consumer so attempting to "explicitly" return a boolean should & will yield a compilation error.






              share|improve this answer























              • I believe that this is the answer, but I am still having trouble seeing it clearly. The lambda spec explicitly distinguishes between lambdas with expression bodies and lambdas with block bodies, whereas void-compatibility rule talks specifically about lambdas with a block body and does not mention expression-bodied lambdas. However, both examples in the question are expression-bodies lambdas. I cannot point my finger on exactly that part of the spec that says this. Your quote from Java in Action seems to interpret the spec the same way as you, and I believe that interpretation is correct, I …
                – Jörg W Mittag
                2 hours ago










              • … just can't find where it is actually supported by the spec.
                – Jörg W Mittag
                2 hours ago















              up vote
              1
              down vote













              The Special Void-Compatibility Rule (JLS) says that a lambda that returns void may accept a statement whose return is non-void. In this case, the return is discarded. hence this compiles.



              Stream.of(1,2,3).forEach(i -> list.add(1)); // return value of add is ignored


              To word it a bit differently by quoting Java-8 in Action book:




              If a lambda has a statement expression as its body, it’s compatible
              with a function descriptor that returns void (provided the parameter
              list is compatible too). For example, both of the following lines are
              legal even though the method add of a List returns a boolean and not
              void as expected in the Consumer context (T -> void):




              // Predicate has a boolean return
              Predicate<String> p = s -> list.add(s);
              // Consumer has a void return
              Consumer<String> b = s -> list.add(s);


              As for the second example, this is explicitly trying to return a boolean where it's not expected hence not possible.



              Stream.of(1,2,3).forEach(i -> true);  


              in other words:



              Stream.of(1,2,3).forEach(i -> {return true;});


              As you already know forEach takes a Consumer so attempting to "explicitly" return a boolean should & will yield a compilation error.






              share|improve this answer























              • I believe that this is the answer, but I am still having trouble seeing it clearly. The lambda spec explicitly distinguishes between lambdas with expression bodies and lambdas with block bodies, whereas void-compatibility rule talks specifically about lambdas with a block body and does not mention expression-bodied lambdas. However, both examples in the question are expression-bodies lambdas. I cannot point my finger on exactly that part of the spec that says this. Your quote from Java in Action seems to interpret the spec the same way as you, and I believe that interpretation is correct, I …
                – Jörg W Mittag
                2 hours ago










              • … just can't find where it is actually supported by the spec.
                – Jörg W Mittag
                2 hours ago













              up vote
              1
              down vote










              up vote
              1
              down vote









              The Special Void-Compatibility Rule (JLS) says that a lambda that returns void may accept a statement whose return is non-void. In this case, the return is discarded. hence this compiles.



              Stream.of(1,2,3).forEach(i -> list.add(1)); // return value of add is ignored


              To word it a bit differently by quoting Java-8 in Action book:




              If a lambda has a statement expression as its body, it’s compatible
              with a function descriptor that returns void (provided the parameter
              list is compatible too). For example, both of the following lines are
              legal even though the method add of a List returns a boolean and not
              void as expected in the Consumer context (T -> void):




              // Predicate has a boolean return
              Predicate<String> p = s -> list.add(s);
              // Consumer has a void return
              Consumer<String> b = s -> list.add(s);


              As for the second example, this is explicitly trying to return a boolean where it's not expected hence not possible.



              Stream.of(1,2,3).forEach(i -> true);  


              in other words:



              Stream.of(1,2,3).forEach(i -> {return true;});


              As you already know forEach takes a Consumer so attempting to "explicitly" return a boolean should & will yield a compilation error.






              share|improve this answer














              The Special Void-Compatibility Rule (JLS) says that a lambda that returns void may accept a statement whose return is non-void. In this case, the return is discarded. hence this compiles.



              Stream.of(1,2,3).forEach(i -> list.add(1)); // return value of add is ignored


              To word it a bit differently by quoting Java-8 in Action book:




              If a lambda has a statement expression as its body, it’s compatible
              with a function descriptor that returns void (provided the parameter
              list is compatible too). For example, both of the following lines are
              legal even though the method add of a List returns a boolean and not
              void as expected in the Consumer context (T -> void):




              // Predicate has a boolean return
              Predicate<String> p = s -> list.add(s);
              // Consumer has a void return
              Consumer<String> b = s -> list.add(s);


              As for the second example, this is explicitly trying to return a boolean where it's not expected hence not possible.



              Stream.of(1,2,3).forEach(i -> true);  


              in other words:



              Stream.of(1,2,3).forEach(i -> {return true;});


              As you already know forEach takes a Consumer so attempting to "explicitly" return a boolean should & will yield a compilation error.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited 2 hours ago

























              answered 3 hours ago









              Aomine

              36.5k62961




              36.5k62961












              • I believe that this is the answer, but I am still having trouble seeing it clearly. The lambda spec explicitly distinguishes between lambdas with expression bodies and lambdas with block bodies, whereas void-compatibility rule talks specifically about lambdas with a block body and does not mention expression-bodied lambdas. However, both examples in the question are expression-bodies lambdas. I cannot point my finger on exactly that part of the spec that says this. Your quote from Java in Action seems to interpret the spec the same way as you, and I believe that interpretation is correct, I …
                – Jörg W Mittag
                2 hours ago










              • … just can't find where it is actually supported by the spec.
                – Jörg W Mittag
                2 hours ago


















              • I believe that this is the answer, but I am still having trouble seeing it clearly. The lambda spec explicitly distinguishes between lambdas with expression bodies and lambdas with block bodies, whereas void-compatibility rule talks specifically about lambdas with a block body and does not mention expression-bodied lambdas. However, both examples in the question are expression-bodies lambdas. I cannot point my finger on exactly that part of the spec that says this. Your quote from Java in Action seems to interpret the spec the same way as you, and I believe that interpretation is correct, I …
                – Jörg W Mittag
                2 hours ago










              • … just can't find where it is actually supported by the spec.
                – Jörg W Mittag
                2 hours ago
















              I believe that this is the answer, but I am still having trouble seeing it clearly. The lambda spec explicitly distinguishes between lambdas with expression bodies and lambdas with block bodies, whereas void-compatibility rule talks specifically about lambdas with a block body and does not mention expression-bodied lambdas. However, both examples in the question are expression-bodies lambdas. I cannot point my finger on exactly that part of the spec that says this. Your quote from Java in Action seems to interpret the spec the same way as you, and I believe that interpretation is correct, I …
              – Jörg W Mittag
              2 hours ago




              I believe that this is the answer, but I am still having trouble seeing it clearly. The lambda spec explicitly distinguishes between lambdas with expression bodies and lambdas with block bodies, whereas void-compatibility rule talks specifically about lambdas with a block body and does not mention expression-bodied lambdas. However, both examples in the question are expression-bodies lambdas. I cannot point my finger on exactly that part of the spec that says this. Your quote from Java in Action seems to interpret the spec the same way as you, and I believe that interpretation is correct, I …
              – Jörg W Mittag
              2 hours ago












              … just can't find where it is actually supported by the spec.
              – Jörg W Mittag
              2 hours ago




              … just can't find where it is actually supported by the spec.
              – Jörg W Mittag
              2 hours ago










              up vote
              0
              down vote













              forEach() as a Consumer as the one and only parameter therefore you need to give an implemention of the method accept() which returns void so on the second example you're implementing a method with the given assinature static boolean method(int).






              share|improve this answer

















              • 3




                Can you explain, why list.add(1), an expression that evaluates to true is a correct implementation of a Consumer, whereas true, an expression that evaluates to true, is an incorrect implementation?
                – Jörg W Mittag
                3 hours ago










              • Like other people said before if you expand the lambda with the { } you'll get an expression on first case and an invalid statement at second.
                – chriptus13
                2 hours ago










              • If you expand the lambda with braces, you get a syntax error for the second example, which is however not what the OP is getting. He is getting a type error, which is something completely different.
                – Jörg W Mittag
                2 hours ago






              • 2




                As was pointed out in another answer, the reason is void-compatibility, not syntax.
                – Jörg W Mittag
                2 hours ago










              • If you don't use the brackets it either is a value which gets translated to a return or a method call.
                – chriptus13
                2 hours ago















              up vote
              0
              down vote













              forEach() as a Consumer as the one and only parameter therefore you need to give an implemention of the method accept() which returns void so on the second example you're implementing a method with the given assinature static boolean method(int).






              share|improve this answer

















              • 3




                Can you explain, why list.add(1), an expression that evaluates to true is a correct implementation of a Consumer, whereas true, an expression that evaluates to true, is an incorrect implementation?
                – Jörg W Mittag
                3 hours ago










              • Like other people said before if you expand the lambda with the { } you'll get an expression on first case and an invalid statement at second.
                – chriptus13
                2 hours ago










              • If you expand the lambda with braces, you get a syntax error for the second example, which is however not what the OP is getting. He is getting a type error, which is something completely different.
                – Jörg W Mittag
                2 hours ago






              • 2




                As was pointed out in another answer, the reason is void-compatibility, not syntax.
                – Jörg W Mittag
                2 hours ago










              • If you don't use the brackets it either is a value which gets translated to a return or a method call.
                – chriptus13
                2 hours ago













              up vote
              0
              down vote










              up vote
              0
              down vote









              forEach() as a Consumer as the one and only parameter therefore you need to give an implemention of the method accept() which returns void so on the second example you're implementing a method with the given assinature static boolean method(int).






              share|improve this answer












              forEach() as a Consumer as the one and only parameter therefore you need to give an implemention of the method accept() which returns void so on the second example you're implementing a method with the given assinature static boolean method(int).







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered 3 hours ago









              chriptus13

              599




              599








              • 3




                Can you explain, why list.add(1), an expression that evaluates to true is a correct implementation of a Consumer, whereas true, an expression that evaluates to true, is an incorrect implementation?
                – Jörg W Mittag
                3 hours ago










              • Like other people said before if you expand the lambda with the { } you'll get an expression on first case and an invalid statement at second.
                – chriptus13
                2 hours ago










              • If you expand the lambda with braces, you get a syntax error for the second example, which is however not what the OP is getting. He is getting a type error, which is something completely different.
                – Jörg W Mittag
                2 hours ago






              • 2




                As was pointed out in another answer, the reason is void-compatibility, not syntax.
                – Jörg W Mittag
                2 hours ago










              • If you don't use the brackets it either is a value which gets translated to a return or a method call.
                – chriptus13
                2 hours ago














              • 3




                Can you explain, why list.add(1), an expression that evaluates to true is a correct implementation of a Consumer, whereas true, an expression that evaluates to true, is an incorrect implementation?
                – Jörg W Mittag
                3 hours ago










              • Like other people said before if you expand the lambda with the { } you'll get an expression on first case and an invalid statement at second.
                – chriptus13
                2 hours ago










              • If you expand the lambda with braces, you get a syntax error for the second example, which is however not what the OP is getting. He is getting a type error, which is something completely different.
                – Jörg W Mittag
                2 hours ago






              • 2




                As was pointed out in another answer, the reason is void-compatibility, not syntax.
                – Jörg W Mittag
                2 hours ago










              • If you don't use the brackets it either is a value which gets translated to a return or a method call.
                – chriptus13
                2 hours ago








              3




              3




              Can you explain, why list.add(1), an expression that evaluates to true is a correct implementation of a Consumer, whereas true, an expression that evaluates to true, is an incorrect implementation?
              – Jörg W Mittag
              3 hours ago




              Can you explain, why list.add(1), an expression that evaluates to true is a correct implementation of a Consumer, whereas true, an expression that evaluates to true, is an incorrect implementation?
              – Jörg W Mittag
              3 hours ago












              Like other people said before if you expand the lambda with the { } you'll get an expression on first case and an invalid statement at second.
              – chriptus13
              2 hours ago




              Like other people said before if you expand the lambda with the { } you'll get an expression on first case and an invalid statement at second.
              – chriptus13
              2 hours ago












              If you expand the lambda with braces, you get a syntax error for the second example, which is however not what the OP is getting. He is getting a type error, which is something completely different.
              – Jörg W Mittag
              2 hours ago




              If you expand the lambda with braces, you get a syntax error for the second example, which is however not what the OP is getting. He is getting a type error, which is something completely different.
              – Jörg W Mittag
              2 hours ago




              2




              2




              As was pointed out in another answer, the reason is void-compatibility, not syntax.
              – Jörg W Mittag
              2 hours ago




              As was pointed out in another answer, the reason is void-compatibility, not syntax.
              – Jörg W Mittag
              2 hours ago












              If you don't use the brackets it either is a value which gets translated to a return or a method call.
              – chriptus13
              2 hours ago




              If you don't use the brackets it either is a value which gets translated to a return or a method call.
              – chriptus13
              2 hours ago










              up vote
              -2
              down vote













              forEach(Consumer<? super T> action) is asking for an action (some process to be done with the element). It needs a method name, not a variable. The return type of the given method doesn't matter.




              Performs an action for each element of this stream.



              ...



              Parameters




              • action - a non-interfering action to perform on the
                elements


              Stream (Java Platform SE 8)







              share|improve this answer



























                up vote
                -2
                down vote













                forEach(Consumer<? super T> action) is asking for an action (some process to be done with the element). It needs a method name, not a variable. The return type of the given method doesn't matter.




                Performs an action for each element of this stream.



                ...



                Parameters




                • action - a non-interfering action to perform on the
                  elements


                Stream (Java Platform SE 8)







                share|improve this answer

























                  up vote
                  -2
                  down vote










                  up vote
                  -2
                  down vote









                  forEach(Consumer<? super T> action) is asking for an action (some process to be done with the element). It needs a method name, not a variable. The return type of the given method doesn't matter.




                  Performs an action for each element of this stream.



                  ...



                  Parameters




                  • action - a non-interfering action to perform on the
                    elements


                  Stream (Java Platform SE 8)







                  share|improve this answer














                  forEach(Consumer<? super T> action) is asking for an action (some process to be done with the element). It needs a method name, not a variable. The return type of the given method doesn't matter.




                  Performs an action for each element of this stream.



                  ...



                  Parameters




                  • action - a non-interfering action to perform on the
                    elements


                  Stream (Java Platform SE 8)








                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited 3 hours ago

























                  answered 3 hours ago









                  Roshana Pitigala

                  4,59662347




                  4,59662347






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.





                      Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                      Please pay close attention to the following guidance:


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53794839%2fwhy-does-foreachval-list-add-compile-whereas-foreachval-true-doesn%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Quarter-circle Tiles

                      build a pushdown automaton that recognizes the reverse language of a given pushdown automaton?

                      Mont Emei