Skip to content

IfElseIfConstructToSwitch removes logic during migration when Type-Casts are used #1108

@meyerimx

Description

@meyerimx

What version of OpenRewrite are you using?

I am using

  • OpenRewrite v8.82.0
  • Maven/Gradle plugin v6.40.0
  • rewrite-migrate-java v3.35.0

How are you running OpenRewrite?

I am using the Maven plugin, and my project is a single module project.

<plugin>
  <groupId>org.openrewrite.maven</groupId>
  <artifactId>rewrite-maven-plugin</artifactId>
  <version>6.40.0</version>
  <configuration>
    <activeRecipes>
      <recipe>org.openrewrite.java.migrate.lang.IfElseIfConstructToSwitch</recipe>
    </activeRecipes>
  </configuration>
  <dependencies>
    <dependency>
      <groupId>org.openrewrite.recipe</groupId>
      <artifactId>rewrite-migrate-java</artifactId>
      <version>3.35.0</version>
    </dependency>
  </dependencies>
</plugin>

What is the smallest, simplest way to reproduce the problem?

public class A {
  void test (Object o) {
    if (o instanceof String s) {
      System.out.println(s);
    }
    else if (o instanceof Integer i) {
      System.out.println(i);
    }
    else if (o instanceof Boolean b) {
      System.out.println(b);
    }
    else if (o != null) {
      System.out.println(o);
    }
  }
}

What did you expect to see?

Either no change (if it's not possible or not in scope for this recipe to migrate this) or something like this:

public class A {
  void test (Object o) {
    switch (o) {
      case String s -> System.out.println(s);
      case Integer i -> System.out.println(i);
      case Boolean b -> System.out.println(b);
      case null -> {}
      default -> {
        System.out.println(o);
      }
    }
  }
}

What did you see instead?

The last else if content was removed. In reality this of course was a more logic than just a print statement.

public class A {
  void test (Object o) {
    switch (o) {
      case String s -> System.out.println(s);
      case Integer i -> System.out.println(i);
      case Boolean b -> System.out.println(b);
      case null, default -> {}
    }
  }
}

What is the full stack trace of any errors you encountered?

No errors shown in the output.

Are you interested in contributing a fix to OpenRewrite?

No

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type
    No fields configured for issues without a type.

    Projects

    Status

    Done

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions