I have been doing Java for a long time and started Scala about 6 months ago. I love the language. One thing that I discovered is that there are multiple ways to do things. I don’t know if it is because of the nature of the language or because it’s still young and evolving and idioms and best practices haven’t emerged.
What surprises me is I have always been a python over perl person where:
“There should be one– and preferably only one –obvious way to do it.”
makes more sense to me than
“There’s more than one way to do it”.
I’m interested to know where you think Scala fit on this scale and why?
Quotes: Python PEP20 and Perl quote
My experience with Scala is that there is more than one way to do things, but relatively few “best” ways to do things. The library has very few gratuitous options for doing things different ways; when it does so, it’s usually to enable extra expressiveness or compactness or efficiency in a subset of cases.
For example, if you want to sum an array of integers, you could be completely procedural, which would generate code that was as fast as possible, at the expense of being a little clunky–but if this is really time-critical code, this is the unique best way to solve the problem:
There are equally general functional approaches that are slower when working with primitives (this may change with @specialized in 2.8) but leave you with less tedium:
And then there are slightly less general functional constructs that are designed for just this sort of problem (since it comes up a lot) and this is “best” if you want clean, compact code:
And sometimes there are very non-general constructs to do exactly what you want; in Scala 2.8, for example:
So you get a continuum of choices with tradeoffs in general power, compactness, clarity, and speed. If you can assume that the code needs only to be accessible to people who are quite familiar with Scala, and you know whether you need the absolute best possible performance or not, the good choices are usually rather limited. But, because of the expressive power of the language and library, there are usually many possible if suboptimal ways to do things.