Java Reference
In-Depth Information
def apply(tweet: String): Boolean = tweet.length() > 60
}
Because the variable isLongTweet holds an object of type Function1, you can call the method
apply, which can be seen as calling the function:
As in Java, you could do the following:
Function<String, Boolean> isLongTweet = (String s) -> s.length() > 60;
boolean long = isLongTweet.apply("A very short tweet");
To use lambda expressions, Java provides several built-in functional interfaces such as Predicate,
Function, and Consumer. Scala provides traits (you can think of traits as interfaces for now until
we describe them in the next section) to achieve the same thing: Function0 (a function with 0
parameters and a return result) up to Function22 (a function with 22 parameters), which all
define the method apply.
Another cool trick in Scala is that you can call the method apply using syntactic sugar that looks
more like a function call:
The compiler automatically converts a call f(a) into f.apply(a) and, more generally, a call f(a1, ...,
an) into f.apply(a1, ..., an), if f is an object that supports the method apply (note that apply can
have any number of arguments).
Closures
In chapter 3 we commented on whether lambda expressions in Java constitute closures. To
refresh, a closure is an instance of a function that can reference nonlocal variables of that
function with no restrictions. But lambda expressions in Java 8 have a restriction: they can't
modify the content of local variables of a method in which the lambda is defined. Those
variables have to be implicitly final. It helps to think that lambdas close over values, rather
than variables .
In contrast, anonymous functions in Scala can capture variables themselves, not the values to
which the variables currently refer. For example, the following is possible in Scala:
 
Search WWH ::




Custom Search