Skip to content

Conversation

bannmann
Copy link
Contributor

@bannmann bannmann commented Dec 7, 2024

- This avoids unchecked warnings at call sites.
- See https://docs.oracle.com/javase/specs/jls/se21/html/jls-9.html#jls-9.6.4.7 for details.
@jlerbsc
Copy link
Collaborator

jlerbsc commented Dec 7, 2024

For information, JP is currently compiled in Java 8.

@bannmann
Copy link
Contributor Author

bannmann commented Dec 7, 2024

Hm, it turns out @SafeVarargs can only be used on final methods. And default methods on interfaces cannot be final. So I guess users have to live with Unchecked generics array creation for varargs parameter warnings whenever calling findAncestor() (or add @SuppressWarnings("unchecked") to their call site).

Alternatively, one might add an overload that accepts a single ancestor class. That overload would not suffer from this problem.

Come to think of it, having that overload might be a good idea anyway - the current findAncestor(Class<N>... types) signature can in fact be called without any arguments (someNode.findAncestor()), which would always return an empty Optional. It would be better if that would trigger a compilation error.

Other APIs tackle this by having non-vararg overloads that combine a fixed argument with varargs. So instead of findAncestor(Class<N>... types) we would have:

  1. findAncestor(Class<N> type)
  2. findAncestor(Class<N> type, Class<N>... types)

When passing a single argument, the Java compiler would then prefer the first version, and use the second if there are more types. Most importantly, someNode.findAncestor() would no longer compile. (Of course that would constitute a breaking change, so it might require deprecation of the old version and adding the new ones with different names.)

@bannmann
Copy link
Contributor Author

bannmann commented Dec 7, 2024

For information, JP is currently compiled in Java 8.

Oh, I didn't know that. Anyway, @SafeVarargs is the same in Java 8.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants