Skip to content

Commit b1a674f

Browse files
committed
Add explanation about scala specific behavior
1 parent ef42361 commit b1a674f

File tree

1 file changed

+18
-1
lines changed

1 file changed

+18
-1
lines changed

rules/S126/scala/rule.adoc

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ The requirement for a final ``++else++`` statement is defensive programming.
77

88
The ``++else++`` statement should either take appropriate action or contain a suitable comment as to why no action is taken. This is consistent with the requirement to have a final ``++case _++`` clause in a ``++match++``.
99

10+
In Scala, this rule also applies when an ``++if++`` statement without an ``++else++`` clause appears on the right-hand side of an assignment. Since Scala treats ``++if++`` as an expression that returns a value, omitting the ``++else++`` clause results in the assignment receiving ``++Unit++`` (represented as ``++()++'') when the condition is false, which is typically unintended and can lead to type errors or unexpected behavior.
11+
1012
=== Noncompliant code example
1113

1214
[source,scala]
@@ -15,7 +17,13 @@ if (x == 0) {
1517
doSomething
1618
} else if (x == 1) {
1719
doSomethingElse
18-
}
20+
}
21+
----
22+
[source,scala]
23+
----
24+
val result = if (x == 0) {
25+
"zero"
26+
}
1927
----
2028

2129
=== Compliant solution
@@ -31,6 +39,15 @@ if (x == 0) {
3139
}
3240
----
3341

42+
[source,scala]
43+
----
44+
val result = if (x == 0) {
45+
"zero"
46+
} else {
47+
"not zero"
48+
}
49+
----
50+
3451
=== Exceptions
3552

3653
When all branches of an ``++if++``-``++else if++`` end with ``++return++``, ``++break++`` or ``++throw++``, the code that comes after the ``++if++`` implicitly behaves as if it was in an ``++else++`` clause. This rule will therefore ignore that case.

0 commit comments

Comments
 (0)