Java

Java

Made by DeepSource

Redundant cast of return value JAVA-W1067

Anti-pattern
Major

The return value of a method call should not be cast if it is used in an expression that expects a value of the same type that the method is returning.

Casting the return value of a method is generally considered bad practice because it can lead to unnecessary complexity and makes the code harder to read.

Unnecessary casting can also be confusing if the method's return type is either the same as the type of the cast or if the return type inherits from the cast type.

Bad Practice

public List<String> manyStrings() {
    return List.of("a", "b");
}

for (String s : (List<String>) manyStrings()) { // ... }
public String oneString() {
    return "ab";
}

Object value = oneString();

Recommended

Consider removing the redundant casts.

public List<String> manyStrings() {
    return List.of("a", "b");
}

for (String s : manyStrings()) { // ... }
public String oneString() {
    return "ab";
}

Object value = oneString();

References