openrewrite / rewrite-migrate-java

OpenRewrite recipes for migrating to newer versions of Java.
Apache License 2.0
111 stars 75 forks source link

Skip `var` replacement when the type cannot fully be resolved #607

Closed uhafner closed 1 week ago

uhafner commented 1 week ago

When a variable is set by the return value of a method with a generic return type, then the type cannot be replaced with var. In such cases the UseVarForObject recipe should skip such replacements.

Example failing test case:

    @Test
    void genericTypeInMethod() {
        rewriteRun(
          java(
            """
              package example;

              class Global {
                  static <T> T cast(Object o) {
                      return (T) o;
                  }
              }
              class User {
                  public String test() {
                      Object o = "Hello";
                      String string = Global.cast(o);
                      return string;
                  }
              }
              """,
              """
              package example;

              class Global {
                  static <T> T cast(Object o) {
                      return (T) o;
                  }
              }
              class User {
                  public String test() {
                      var o = "Hello";
                      String string = Global.cast(o);
                      return string;
                  }
              }
              """
          )
        );
    }

This test currently creates the following code that does not compile (on JDK 21).

package example;

class Global {
    static <T> T cast(Object o) {
        return (T) o;
    }
}
class User {
    public String test() {
        var o = "Hello";
        var string = Global.cast(o);
        return string;
    }
}