Advertisement
Guest User

Untitled

a guest
Mar 27th, 2017
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.06 KB | None | 0 0
  1. # Functional Interfaces
  2.  
  3. ```java
  4. @FunctionalInterface
  5. public interface Runnable {
  6. public void run();
  7. }
  8. ```
  9.  
  10. A Functional Interface is an interface with exactly one abstract method.
  11. We can optionally annotate with *@FunctionalInterface*, so compilation will
  12. fail if a second abstract method is added to the class.
  13.  
  14.  
  15. -----------------
  16.  
  17. ```java
  18. Runnable runnable = new Runnable() {
  19. @Override
  20. public void run() {
  21. System.out.println("Hello, world!");
  22. }
  23. }
  24. ```
  25.  
  26. Traditionally, to create a *Runnable* instance we often use an anonymous class,
  27. overriding the *run* method inline.
  28.  
  29.  
  30.  
  31.  
  32.  
  33. -----------------
  34. # Lambda Functions
  35. ```java
  36. Runnable runnable = () -> System.out.println("Hello, world!");
  37.  
  38. runnable.run(); // prints "Hello, world!"
  39. ```
  40.  
  41. Lambda functions allow us to create instances of Functional Interfaces with a
  42. cleaner, more succinct syntax.
  43.  
  44.  
  45.  
  46.  
  47.  
  48. -----------------
  49.  
  50. ```java
  51. @FunctionalInterface
  52. public interface Consumer<T> {
  53. public void accept(T t);
  54. }
  55.  
  56. ```
  57.  
  58. *Consumer* is another Functional Interface for functions that take a single
  59. generic parameter but return *void*. A similar Functional Interface is used
  60. extensively in Akka when we define the behavior of our *Actor*s.
  61.  
  62.  
  63. -----------------
  64.  
  65. ```java
  66. Consumer<String> consumer = (String s) -> System.out.println(s);
  67.  
  68. consumer.accept("Happy hAkking!"); // prints "Happy hAkking!"
  69. ```
  70.  
  71. -----------------
  72.  
  73. ```java
  74. @FunctionalInterface
  75. public interface Function<T, R> {
  76. public R apply(T t);
  77. }
  78.  
  79. Function<String, Integer> toInt = s -> Integer.parseInt(s);
  80.  
  81. toInt.apply("1234") // returns 1234
  82.  
  83. Function<User, Integer> insertUser = user -> {
  84. String encryptedPassword = encrypt(user.password);
  85. Integer id = db.insert(user, encryptedPassword);
  86. return id;
  87. };
  88. ```
  89.  
  90. If your function body is only one line, you can omit the *return* keyword and
  91. the result of that single line expression will be returned. A multi-line
  92. function body must be wrapped in braces and include a *return* statement.
  93.  
  94. Also notice that you can omit the type of the parameter of a lambda function
  95. if it is possible for the compiler to infer the type.
  96.  
  97.  
  98. ------------------
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement