Is the class body syntax just a habit or for a reason?

Is there a reason why the syntax is

class Foo { }


def foo = {}
Val bar = {}

I’ve been assuming it was just a hangover from C. Is there something important to the syntax that I should be considering?

The syntax for def and val doesn’t actually have the curly braces. In both cases, the right side of the = is an expression like def foo = 2+2. If you want multiple statements, you use curly braces to make a longer expression. A class is not a single expression. By it’s nature it is almost always multiple declaration statements. As a result, the curly braces are required as part of the syntax. The lack of the = is that because it isn’t an expression in the curly braces, so that grouping of declarations doesn’t have a value the way it does for def or val.

Sorry, I meant the missing “=“ I should have used

var bar=???
def foo=???

for my examples. The curly brace is just there to tie multiple statements together. Given types and data structures have more than a single function or information slot, classes/traits will almost always need them.

The body of a class isn’t an expression though, it is a statement. Whether you write val bar = 5 or val bar = { 5 }, the right side of the = is an expression whose value you wish to associate with the name val. The body of a class, on the other hand, is a collection of declaration statements, not an expression. As such, the curly braces are required to hold any body you provide and they creators of Scala decided that the = didn’t make sense in that context.

If the class has no body then in Scala you don’t need the braces.

If your question is why when it does have a body the syntax uses braces, well why not? Especially if it has more than one statement or declaration in it. If it only has one, and you didn’t have braces, how would it know that it’s part of it? There’s no equals sign, and there shouldn’t be, because it’s not defining an equivalence or substitutability as with val/var/def. And unlike if, else, while, and for/for-yield, it is not required to contain anything (and often doesn’t). So you need some syntax.

Besides, it lines up nicely with type refinement syntax.

@nafg Thanks, that makes sense. I was wondering why. It is meaningful, which is what I wanted to understand. It fits in with the brace notation with maps, &c. You’ve been helpful.