3

The scala style checker says that while loops are deprecated if you’re using a strict functional style - http://www.scalastyle.org/rules-dev.html#org_scalastyle_scalariform_WhileChecker. I found 1 solution - Is there any advantage to avoiding while loops in Scala? This says mutability will ensure that, on the long run, you'll introduce bugs with a while pattern. How can this happen? Why is there no check for for loop if immutability is highly restricted? I have a simple use case where I have to remove all the occurrences of substring from a string that are present at the end. I could find a solution for it because of which I was using loops. Example - String is "IABCFGHUABCABC" and subtring is "ABC". String output should be "IABCFGHU" where all the trailing occurrences of substring is removed. Is there any non imperative and recommended way to solve this problem using scala?

  • 1
    Well... It all boils down to the difference between `Functional` and `Imperitive` paradigms. In functional philosophy you think of your program as a series of computations while avoiding any change of in existing state (only new additions are allowed). Now just think... if you are not allowed to change the value assigned to any variable, then your while loops will automatically become useless. Also... you are confusing `for-comprehensions` with `for-loops`. – sarveshseri Mar 29 '18 at 10:12

1 Answers1

5

Why is there no check for for loop if immutability is highly restricted?

Because unlike in C-style for loops, there's no mutability in Scala for:

for (i <- <something>) {
  <body>
}

is just another way to write the method call <something>.foreach { i => <body> }.

Is there any non imperative and recommended way to solve this problem using scala?

Yes, of course. As the question you linked says, you can use tail recursion. I won't provide code, but the idea is: if the string doesn't end with the substring, return it; if it does, remove that ending and call the function again with new arguments. You should think on why this will ultimately return the desired result.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487