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;
}
}
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 theUseVarForObject
recipe should skip such replacements.Example failing test case:
This test currently creates the following code that does not compile (on JDK 21).