Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Functional Interfaces
- ```java
- @FunctionalInterface
- public interface Runnable {
- public void run();
- }
- ```
- A Functional Interface is an interface with exactly one abstract method.
- We can optionally annotate with *@FunctionalInterface*, so compilation will
- fail if a second abstract method is added to the class.
- -----------------
- ```java
- Runnable runnable = new Runnable() {
- @Override
- public void run() {
- System.out.println("Hello, world!");
- }
- }
- ```
- Traditionally, to create a *Runnable* instance we often use an anonymous class,
- overriding the *run* method inline.
- -----------------
- # Lambda Functions
- ```java
- Runnable runnable = () -> System.out.println("Hello, world!");
- runnable.run(); // prints "Hello, world!"
- ```
- Lambda functions allow us to create instances of Functional Interfaces with a
- cleaner, more succinct syntax.
- -----------------
- ```java
- @FunctionalInterface
- public interface Consumer<T> {
- public void accept(T t);
- }
- ```
- *Consumer* is another Functional Interface for functions that take a single
- generic parameter but return *void*. A similar Functional Interface is used
- extensively in Akka when we define the behavior of our *Actor*s.
- -----------------
- ```java
- Consumer<String> consumer = (String s) -> System.out.println(s);
- consumer.accept("Happy hAkking!"); // prints "Happy hAkking!"
- ```
- -----------------
- ```java
- @FunctionalInterface
- public interface Function<T, R> {
- public R apply(T t);
- }
- Function<String, Integer> toInt = s -> Integer.parseInt(s);
- toInt.apply("1234") // returns 1234
- Function<User, Integer> insertUser = user -> {
- String encryptedPassword = encrypt(user.password);
- Integer id = db.insert(user, encryptedPassword);
- return id;
- };
- ```
- If your function body is only one line, you can omit the *return* keyword and
- the result of that single line expression will be returned. A multi-line
- function body must be wrapped in braces and include a *return* statement.
- Also notice that you can omit the type of the parameter of a lambda function
- if it is possible for the compiler to infer the type.
- ------------------
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement