if
can be moved inside the loop64 for (_ <- array.indices) {
65 var swap = false
66
67 for (j <- 0 to array.length - 2) {68 if (array(j) > array(j + 1)) {69 val temp = array(j)70 array(j) = array(j + 1)71 array(j + 1) = temp72 swap = true73 }74 }75 if (!swap) {
76 break()
77 }
Description
Scala's for
loop has 2 elements — enumerator generator that defines the range for the loop and an enumerator guard, a condition that must be satisfied before the loop's body can be executed. If your for
loop has a single statement in its body and this statement is an if
condition without an else
clause, it is recommended that you move this explicit if
condition to the loop.
Bad Practice
for (i <- lb to ub) {
if (i % 2 == 0) {
println(i)
}
}
Recommended
for (i <- lb to ub if i % 2 == 0) {
println(i)
}