Class UnnamedPatternsVariablesPreviewExamples

java.lang.Object
net.jrodolfo.java_evolution.java21.UnnamedPatternsVariablesPreviewExamples

public class UnnamedPatternsVariablesPreviewExamples extends Object
Demonstrates unnamed patterns and variables as a Java 21 preview feature.

Sometimes Java syntax requires a variable name even though the program intentionally ignores the value. Before this feature, developers often used names such as ignored or unused. The underscore makes that intent part of the language: the value is deliberately not available for later use.

The feature became final in Java 22 as unnamed variables and patterns. This The syntax shown here is also the syntax that became final in Java 22, so it remains faithful to the Java 21 preview while this class preserves the historical preview label.

  • Constructor Details

    • UnnamedPatternsVariablesPreviewExamples

      public UnnamedPatternsVariablesPreviewExamples()
  • Method Details

    • countWithoutUsingElements

      public int countWithoutUsingElements(Iterable<String> values)
      Uses an unnamed variable where the value is intentionally ignored.

      The loop visits every element, but the body only needs to count visits. The underscore says the element value is irrelevant.

      Parameters:
      values - values to count
      Returns:
      how many values were visited
    • canParseInteger

      public boolean canParseInteger(String text)
      Uses an unnamed catch parameter when the exception object is not needed.

      The code only needs to know that parsing failed. It does not need the exception object itself.

      Parameters:
      text - numeric text
      Returns:
      whether the text can be parsed
    • startsAtX

      public boolean startsAtX(Object shape, int expectedStartX)
      Uses unnamed patterns for record components that are not needed.

      The first point's x coordinate is useful, but neither y coordinate nor the second point is needed. The underscores make those intentional omissions visible in the pattern.

      Parameters:
      shape - value to inspect
      expectedStartX - x coordinate required for the first point
      Returns:
      whether the value is a line whose first point has the requested x coordinate