rewrite-migrate-java
rewrite-migrate-java copied to clipboard
Support for Ternary Operator assignments in var context
What problem are you trying to solve?
While developing #217 I discovered that handling, especially detecting ternary operator assignments, is hard. With this issue, Rewrite become able to apply ´var´ to ternary operator assignments.
What precondition(s) should be checked before applying this recipe?
var should not be applied to variable declarations where:
- the type of the ternary operator and the left-hand side don't match
- the type is byte or short
- only null is assigned
- the declaration is outside a method declaration
Describe the situation before applying the recipe
class A {
void foo(String bar) {
int i1 = bar != null ? 3 : 5;
Integer i2 = bar != null ? 3 : null;
Integer i3 = bar == null ? null : bar.lenght();
Integer i4 = bar != null ? throw new IlligalArgumentExcpetion() : -1;
int i5 = bar != null ? bar.lenght() : 0;
float f1 = bar != null ? 3f : 3.5;
}
}
Describe the situation after applying the recipe
class A {
void foo(String bar) {
var i1 = bar != null ? 3 : 5;
var i2 = bar != null ? 3 : null;
var i3 = bar == null ? null : bar.lenght();
var i4 = bar != null ? throw new IlligalArgumentExcpetion() : -1;
var i5 = bar != null ? bar.lenght() : 0;
var f1 = bar != null ? 3f : 3.5;
}
}
Have you considered any alternatives or workarounds?
An alternative would be to skip every ternary operator, this would lead to no 100% local variable type inference for rewrite.
Any additional context
It would be nice to write a separate recipe for this and integrate them later on as global var refactoring.
Are you interested in contributing this recipe to OpenRewrite?
not now.