I follow the C family (PHP is a wannabe!) requirement that a statement that spans over multiple lines must be enclosed in curlies.
Scala avoids parse errors in this code from O’Reilly’s Programming Scala.
def apply(specification: String): Option[Widget] = specification match {
case ButtonExtractorRE(label) => new Some(new Button(label))
case TextFieldExtractorRE(text) => new Some(new TextField(text))
case _ => None
}
whereas I believe it should look like (the body of the function is enclosed):
def apply(specification: String): Option[Widget] = {
specification match {
case ButtonExtractorRE(label) => new Some(new Button(label))
case TextFieldExtractorRE(text) => new Some(new TextField(text))
case _ => None
}
}
while Scala can parse it, can a programmer “get it”? I dont. Am I missing some intuitive idea?
Should I rather avoid such a practice, if it leads to practical problems (like poor readability?
In Scala much more things (including
if,matchandforwithyield) return a result as in other languages. And more data structures are immutable, which often leads to transformation chains ofmap,filter,flatMap,collectetc – which also gives just one result. Last but not least Scala has excellent support for tuples, which means that you often get back a tuple as a single result where other languages have to sort out single values.So in general Scala doesn’t deal as much with variables storing intermediate values as other languages do. That means a function is often just an equation f(a) = b, where b might be quite complex, but is still one chain returning a single result. So it is just naturally to adopt that syntax, which makes immediately clear that you are not juggling with intermediate results, but that you follow a more functional style.
It should be mentioned that functional languages (except the “lispy” family with a quite different syntax) have similar conventions. So if you look at Haskell, F# or Erlang, you usually won’t see any “blocks” for methods. There are structures like
let,caseand (for Haskell)dowhich might look a little bit like blocks, but are expressions as well.