You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

UnnamedPatternsPreview1Aspect.aj 2.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import java.awt.*;
  2. import java.util.List;
  3. import java.util.PriorityQueue;
  4. import java.util.Queue;
  5. import java.util.stream.Collectors;
  6. import java.util.stream.Stream;
  7. /**
  8. * Examples taken from <a href="https://openjdk.org/jeps/443">JEP 443</a>
  9. */
  10. public aspect UnnamedPatternsPreview1Aspect {
  11. public static void main(String[] args) {}
  12. before() : execution(* main(String[])) {
  13. System.out.println(thisJoinPoint);
  14. // An enhanced for loop with side effects
  15. int acc = 0;
  16. final int LIMIT = 2;
  17. for (Order _ : List.of(new Order(), new Order(), new Order())) {
  18. if (acc < LIMIT)
  19. acc++;
  20. }
  21. System.out.println(acc);
  22. // The initialisation of a basic for loop can declare unnamed local variables
  23. for (int i = 0, _ = sideEffect(); i < 2; i++) {
  24. System.out.println(i);
  25. }
  26. // An assignment statement, where the result of the expression on the right hand side is not needed
  27. Queue<Integer> q = new PriorityQueue<>(List.of(1, 2, 3, 4, 5, 6));
  28. while (q.size() >= 3) {
  29. var x = q.remove();
  30. var y = q.remove();
  31. var _ = q.remove();
  32. System.out.println(new Point(x, y));
  33. }
  34. // The same unnamed variable name '_' can be used in multiple assignment statements
  35. q = new PriorityQueue<>(List.of(1, 2, 3, 4, 5, 6));
  36. while (q.size() >= 3) {
  37. var x = q.remove();
  38. var _ = q.remove();
  39. var _ = q.remove();
  40. System.out.println(new Point(x, 0));
  41. }
  42. // Unnamed variables can be used in one or multiple catch blocks
  43. String s = "123xy";
  44. try {
  45. int i = Integer.parseInt(s);
  46. System.out.println(i);
  47. } catch (NumberFormatException _) {
  48. System.out.println("Bad number: " + s);
  49. } catch (Exception _) {
  50. System.out.println("Unexpected error");
  51. }
  52. // Try with resources
  53. try (var _ = ScopedContext.acquire()) {
  54. System.out.println("Doing something within scoped context");
  55. }
  56. // A lambda whose parameter is irrelevant
  57. System.out.println(
  58. Stream.of("one", "two", "three")
  59. .collect(Collectors.toMap(String::toUpperCase, _ -> "NODATA"))
  60. );
  61. }
  62. static int sideEffect() {
  63. System.out.println("side effect");
  64. return 42;
  65. }
  66. static class Order {}
  67. static class ScopedContext implements AutoCloseable {
  68. public static ScopedContext acquire() {
  69. return new ScopedContext();
  70. }
  71. @Override
  72. public void close() {
  73. System.out.println("Closing scoped context");
  74. }
  75. }
  76. }