Skip to content

Java 17 Pattern Matching for Switch (JEP-406) compatibility issue #684

Description

@mcwhitak

With version 1.12.0 google-java-format does not properly recognize imports utilized only during pattern matched switches.

As an example, for the following hierarchy

package example.model;

public sealed interface SealedInterface {}

public non-sealed interface TypeA {}
public non-sealed interface TypeB {}

and a Java file using this hierarchy with a pattern matched switch

package example;

import example.model.SealedInterface;
import example.model.TypeA;
import example.model.TypeB;

public class Main {
  public void apply(SealedInterface sealedInterface) {
    switch(sealedInterface) {
      case TypeA a -> System.out.println("A!");
      case TypeB b -> System.out.println("B!");
    }
  }
}

google-java-format will flag import example.model.TypeA and import example.model.TypeB as unused and candidates for removal.

I've recreated this bug in a small repo that illustrates the issue.

Activity

  1. lorenzleutgeb commented on Nov 19, 2021

    @lorenzleutgeb

    This appears to be a duplicate of #683 (which turns out to not only apply when throwing exceptions).

  2. cushon commented on Nov 19, 2021

    @cushon
    Collaborator

    This is fixed now: the formatter didn't support pattern matching in switches on Java 17 at all, and there was a separate issue specifically about unused imports. Thanks for the report!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions