Java Reference
In-Depth Information
"I love the new features in Java 8",
"How's it going?",
"An SQL query walks into a bar, sees two tables and says 'Can I join you?'"
)
tweets.filter(isJavaMentioned).foreach(println)
tweets.filter(isShortTweet).foreach(println)
Now let's inspect the signature of the built-in method filter:
def filter[T](p: (T) => Boolean): List[T]
You may wonder what the type of the parameter p means (here (T) => Boolean), because in Java
you'd expect a functional interface! This is a new syntax that's not available in Java. It describes
a function type . Here it represents a function that takes an object of type T and returns a
Boolean. In Java this is encoded as a Predicate<T> or Function<T, Boolean>. This is exactly the
same signature as the methods isJava-Mentioned and isShortTweet so you can pass them as
argument to filter. The Java 8 language designers decided not to introduce a similar syntax for
function types in order to keep the language consistent with previous versions. (Introducing too
much new syntax in a new version of the language is seen as too much additional cognitive
overhead.)
15.2.2. Anonymous functions and closures
Scala also supports the concept of anonymous functions . They have a syntax similar to lambda
expressions. In the following example you can assign to a variable named isLongTweet an
anonymous function that checks whether a given tweet is long:
Now in Java, a lambda expression lets you create an instance of a functional interface. Scala has
a similar mechanism. The previous code is syntactic sugar for declaring an anonymous class of
type scala.Function1 (a function of one parameter), which provides the implementation of the
method apply:
val isLongTweet : String => Boolean
= new Function1[String, Boolean] {
 
Search WWH ::




Custom Search