Mitchell Coutinho wrote:Thanks . . .
That's a pleasure
. . . what trips me up is the explanation of why answer C is correct. . . . allowed to omit the parentheses . . . they may either be present or absent. . . .
Yes, as you will have seen from the link I showed you, the
(...) may be present or absent if you reduce the parameter list to exactly one
token. As I said, the wording of the question seems not to be clear to everybody. The
Java® Language Specification (=JLS) says,
If a lambda expression has exactly one formal parameter, and the parameter is specified by an identifier instead of a parameter specifier, then the parentheses around the identifier may be elided.
. . . and I don't think that is much clearer.
As for answer F . . . if the single statement is surrounded by brackets, then the return statement must be used. . . .
Thank you for showing us the additional information about question F .
I am in Britain, so I use the
word “bracket” slightly differently from people in the USA, but please call
{...} “braces.”
Let's see whether the JLS can help:
try this section. Yes, the grammar says that a
LambdaBody (=part right of the
‑>) may be an
Expression or a
Block. If your λ for F reads
i ‑> i == 5, then the body is an expression. If you look up the grammar for
Block (use link on that JLS page), you will see it may contain any number (including 0) of declarations and statements, but it is not allowed to contain plain simple expressions. If you put braces
{...} around the body of the λ, then you are saying it mustn't contain plain expressions. You can however get it to compile by changing all the expressions to statements by prefacing them with
return.
If no custom type has been shown, I believe the type of the λ in question F is either a
Predicate<Integer, Boolean> or an
IntPredicate.