Java Reference
In-Depth Information
off, but they've been included for ease of readability. The body is simply evaluated and
then returned. If the body of the lambda is an expression and not a statement, a re-
turn is implicit. On the contrary, if the body includes more than one statement, a re-
turn must be specified, and it marks return of control back to the caller.
The following code demonstrates a lambda expression that does not contain any ar-
guments:
StringReturn msg = () -> "This is a test";
Let's take a look at how this lambda expression works. In the previous listing, an
object of type StringReturn is returned from the lambda expression. The empty set
of parentheses denotes that there are no arguments being passed to the expression. The
return is implicit, and the string "This is a test" is returned from the lambda
expression to the invoker. The expression in the example is assigned to a variable iden-
tified by msg . Assume that the functional interface, StringReturn , contains an ab-
stract method identified as returnMessage() . In this case, the
msg.returnMessage() method can be invoked to return the string.
The body of a lambda expression can contain any Java construct that an ordinary
method may contain. For instance, suppose a string were passed as an argument to a
lambda expression, and you wanted to return some value that is dependent upon the
string argument. The following lambda expression body contains a block of code,
which returns an int , based upon the string value of the argument passed into the ex-
pression.
ActionCode code = (codestr) -> {
switch(codestr){
case "ACTIVE": return 0;
case "INACTIVE": return 1;
default:
return -1;
}
};
In this example, the ActionCode functional interface is used to infer the return
type of the lambda expression. For clarification, let's see what the interface looks like.
Search WWH ::




Custom Search