Scala scopes.

After some programming with Scala, there are a couple of language features which I really like. One of them is scopes that can evaluate to a value. How does that look like:

Ignore the obvious inefficiencies of the code and take a look at how you can put a block of code inside the inner scope. What's good about that? This inner scope is like a lighweight function. The benefits are:

  • Variables in the function are not seen outside of the scope. Great, because you'll get a compile error if you try to use one of those variables. Once you're working in the scope you know that any variable you declare inside of it won't be used on the outside.

  • You have a logical block of computation that has a clear start and finish, which makes the code easier to read and work with.

  • Unlike a function, you don't need to declare function parameters.

The drawback is of course that this can become an excuse for creating long functions, with a lot of scopes like this one inside of them. If that's avoided, this language feature leads to easier to understand code.