Java 14 Enhanced Switch Statement alerts to rule java:S1121

The introduction to enhanced switch statements was made in Java 14. Refactoring some code and IntelliJ IDEA was stating a switch statement could be changed to the new enhanced switch statement. After using IntelliJ IDEA auto “replace with enhanced switch statement” then SonarLint is alert to java:1121 that " Assignments should not be made from within sub-expressions".

Versions
SonarLint - 6.4.3.42541 - Released 1/27/2022 - SonarLint - IntelliJ IDEs Plugin | Marketplace
Java - Java 17 but enhanced switch statement was in Java 14

Sample Code (before auto replace)

int rand = new Random().nextInt(5);
String temp;
String temp2 = "";

switch (rand) {
	case 1:
		temp = "partial";
		break;
	case 2:
		temp = "whole";
		break;
	case 3:
		temp = "none";
		break;
	default:
		temp = "empty";
		temp2 = "default";
		break;
}

Sample Code (after auto replace)

int rand = new Random().nextInt(5);
String temp;
String temp2 = "";

switch (rand) {
	case 1 -> temp = "partial";
	case 2 -> temp = "whole";
	case 3 -> temp = "none";
	default -> {
		temp = "empty";
		temp2 = "default";
	}
}

* each of the temp assignments alerts on java:s1121

IntelliJ IDEA Inspection Description

Switch statement can be replaced with enhanced ‘switch’

Inspection info: Reports switch statements that can be automatically replaced with enhanced switch statements or expressions.
Example:

  double getPrice(String fruit) {
    // Switch statement can be replaced with enhanced 'switch'
    switch (fruit) {
      case "Apple":
        return 1.0;
      case "Orange":
        return 1.5;
      case "Mango":
        return 2.0;
      default:
        throw new IllegalArgumentException();
    }
  }

After the quick-fix is applied:

  double getPrice(String fruit) {
    return switch (fruit) {
      case "Apple" -> 1.0;
      case "Orange" -> 1.5;
      case "Mango" -> 2.0;
      default -> throw new IllegalArgumentException();
    };
  }

Further Discussion
I understand that the example doesn’t fully translate to proper production code but used for demonstration purposes. I believe the auto replacer uses the assignment in the “test” on the switch since there is multiple things being done by default. Sometimes in the default you want to do more assignments to catch different things not cause in each case.

Also, not sure if this is a rule issue or if in this case the enhanced switch should be avoided due to other clumsy code smell issues.

Thanks
Bruce

1 Like

Hello @bcoveny

I just stumbled into this topic, and I think it makes sense. I created a ticket to improve the situation: SONARJAVA-4219.

Thanks for taking the time to describe the problem.
Best,
Quentin

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.