0

The following is a skeleton of break in scala using util.control.Breaks._ :

        import util.control.Breaks._
        breakable {
            for (oct <- 1 to 4) {
                 if (...) {
              
                 } else {
                    break
                 }
            }
       }

This structure requires remembering several non intuitive names. I do not use break statements every other or third day - but part of that is the difficulty in remembering how to do them. In a number of other popular languages it is dead simple: break out of a loop and you're good.

Is there any mechanism closer to that simple keyword/structure in scala?

WestCoastProjects
  • 58,982
  • 91
  • 316
  • 560
  • Does this answer your question? [How do I break out of a loop in Scala?](https://stackoverflow.com/questions/2742719/how-do-i-break-out-of-a-loop-in-scala) – Tomer Shetah Jan 17 '21 at 17:12
  • @TomerShetah I had seen that - and lifted the `breakable` code from the answer that was least undesirable. So no it does not answer the question. The accepted answer below does give the answer needed. – WestCoastProjects Jan 17 '21 at 17:17
  • And this: https://stackoverflow.com/a/37520961/2359227 – Tomer Shetah Jan 17 '21 at 17:31

1 Answers1

4

No, there isn't. for is not a loop but a syntactic sugar to a chain of functions with closures passed into them. Since the local stack changes, it cannot be translated into some goto instruction like a "normal" break does. To break the execution of arbitrarily nested closures you have to throw an exception, which is what both break and return do to exit early.

For particular situation you can often use something like .filter, .takeWhile, .dropWhile (sometimes with .sliding to look ahead), etc. For situation where you have no better idea, @tailrecursive function is always an option.

In your current example I would probably do:

(1 to 4).takeWhile(...).foreach { oct => ... }

Basically, I would consider every single case individually to write it in a declarative way.

Mateusz Kubuszok
  • 24,995
  • 4
  • 42
  • 64
  • 1
    This probably works fine for normal "work" with scala and is likely the best we will do. I am however trying to use scala for interview type questions : and those types of traditional CS algorithms are difficult to write in a purely declarative manner - especially on the fly if I am tweaking the approach mid stream. – WestCoastProjects Jan 17 '21 at 16:11
  • 2
    For these kind of questions you can remember that Scala does have `var`s and one loop - `while`. And everything that requires low-level, mutability and looping is implemented using `while` in Scala. "Normal" `for`s, `do-while`s and foreaches are just `while`s in disguise. – Mateusz Kubuszok Jan 17 '21 at 16:12
  • 1
    Yes but it does get tiresome to force feed every construct i learnt while doing c (or even java or python) into a `while` . In addition interviewers do not always look kindly on these constructs - justified or not. btw I did accept - since this is probably the correct answer. Don't shoot the messenger. – WestCoastProjects Jan 17 '21 at 16:14
  • 3
    It should be tiresome to discourage you from using it. Imperative code is hard to maintain and so it should be painful to write so that you would write it because you need it, not because you find it easier to write. If you have a use case, then you can bear the pain of writing `while`s. – Mateusz Kubuszok Jan 17 '21 at 16:16
  • 1
    I brought up about interview situations in particular. More flexibility is helpful in these situations than might be expected/required for day-to-day programming. I'm not confident that scala is the right language choice at this point. Will give it a bit more burn but might need to pivot. – WestCoastProjects Jan 17 '21 at 16:23
  • 3
    @StephenBoesch I personally would rethink the questions, if you are interviewers Scala programmers then what is the point to make questions that need imperative programming? – Luis Miguel Mejía Suárez Jan 17 '21 at 16:30
  • 3
    Scala is biased towards _funtional_ and _imperative_ programming. It lets you write imperative code, but it's not primarily optimized towards writing it. If you are not prepared to learn a new approach toward problem solving, it will seem unnecessarily complex. If I went to Java from C and expected it to have `malloc` and `free` I would also feel disappointed. – Mateusz Kubuszok Jan 17 '21 at 16:30
  • 2
    BTW, if I went to interview and the interviewer was expecting me to write some particular implementation rather than just solve the problem and justify my solution I would have some serious doubts about the company. – Mateusz Kubuszok Jan 17 '21 at 16:33
  • 1
    Day to day scala is far superior to java/C etc. As an aside I have written a functionals library for python due to frustration with its imperative focus. It's just that many of these leetcode type algos are focused on problems that tend towards mutability and intricate looping. It is _possible_ to approach these from `@tailrec` recursion etc but I'nynot going to lean on those kinds of constructs when under the gun. Also they lead to imo overly complicated structures for those particular problems. – WestCoastProjects Jan 17 '21 at 16:37
  • 2
    It's getting offtop but: I consider leetcode-based interviews to be an antipattern of recruitment. They show that company has no idea who they need and how to evaluate them. Personally, I quit all interviews that want me to perform some competitive programming test as I see that they are biased towards youngsters who still remember algos from uni rather than people who can learn on the job, are responsible and can talk to business. If you are using such questions then I recommend to change this, as people like me would quit on the spot. – Mateusz Kubuszok Jan 17 '21 at 16:41
  • 1
    It's actually not offtopic : it shows that there is actually some agreement about suitability of scala to these questions (ie it is not much suitable). I don't have a choice: silicon valley has bought wholesale into this approach and google and FB positively do not do scala at all. I avoided those companies for years (with offers or opportunities in hand) for that specific reason. But I'm rethinking that decision. – WestCoastProjects Jan 17 '21 at 16:46
  • Well, do what you need to do. My experiences are that I would rather quit programming altogether rather than go working for a big corporation (including FAANG). The plethora of small to middle companies where I can have some actual impact (and which use Scala) make me confident in that decision. – Mateusz Kubuszok Jan 17 '21 at 16:53
  • That's great! I went that direction for a few years but it has mostly dried up in these parts. – WestCoastProjects Jan 17 '21 at 16:54
  • So far I get more and more offers from Scala. Signify contacts me every once in a while. My only limitation is that I want to work remotely which filters out a lot of jobs, but even that improved a lot during the pandemic. – Mateusz Kubuszok Jan 17 '21 at 16:56
  • Well it's also true that you're much deeper in. I have had to mix in python and javascript a lot in the past two years and the scala was pretty basic for years before that (apache spark flavor vs cats/scalaz pure fp stuff) – WestCoastProjects Jan 17 '21 at 16:59
  • I have 0 Spark experience, it didn't stop me from getting something. Just try a little more. – Mateusz Kubuszok Jan 17 '21 at 17:00
  • Ah I see. The types of problems I'm solving: data engg/ML/AI/Deep Learning are more important to me than the language. That used to lead to Scala (through Spark ) but now leads to python/pyspark or pure python. I'd take scala over python 8 days of the week but I don't get to choose. – WestCoastProjects Jan 17 '21 at 17:03
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/227450/discussion-between-stephenboesch-and-mateusz-kubuszok). – WestCoastProjects Jan 17 '21 at 17:13