These code examples:
import java.util.Observer;
public class Main {
public static void main(String[] args) {
Observer observer = (o, arg) -> {
if (arg != null) {
System.out.println(arg);
}
};
}
}
import java.util.Observer;
public class Main {
public static void main(String[] args) {
Observer observer = (o, arg) -> {
try {
String test = (String) arg;
...
}
catch (ClassCastException e) {
}
};
}
}
are noncompliant with this sonarqube rule:
Lamdbas containing only one statement should not nest this statement in a block : Remove useless curly braces around statement
how can i fix it ?
The body of the lambda expressions can contain any number of statements. If the body of the lambda expression has a single statement, the curly brackets are not mandatory but when there is more than one statement in the body then these must be enclosed in curly brackets.
Different programming languages have various ways to delineate the start and end points of a programming structure, such as a loop, method or conditional statement. For example, Java and C++ are often referred to as curly brace languages because curly braces are used to define the start and end of a code block.
The classification of these curly braces as “useless” is wrong.
You can omit curly braces around a single expression statement, that is, for example, a method invocation, a new
expression, or x++
, x+=y
, etc.
Or you can transform a sole … -> { return x; }
statement into an expression … -> x
.
But you can’t omit curly braces around every single statement.
You can’t fix that. The only thing you can do is file a bug report.
By the way, even then, removing them is not necessarily a readability improvement. It depends…
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With