Why does scala need to write `=` of `def a (): Int = {1}`?

That is a very simple question, why does scala need to write = of def a (): Int = {1} ?
I think that it is because I thought about composing syntax by combining operators.
But I want to know the real reason.
Please tell me when it was someone you know.


Well, the only person who could probably answer that definitively is Martin Odersky (the creator of the Scala language), and I don’t know that he’s on this board.

But it’s worth noting that def foo {1} is legal syntax – but it means something else. Scala defines the version with the = as a function, and the version without as a procedure: a function that, by definition, returns Unit. At the time, spawning somewhat from Java, this made some sense, since side-effecting functions are so common in Java. See this fiddle for an illustration of that.

Over the years, most of the community has come to the conclusion that this was a mistake – the procedure syntax makes it very easy to have accidental bugs (by leaving off the = unintentionally) – and idiomatic Scala has mostly moved away from doing this sort of thing routinely. I think it’s slated to be deprecated and removed down the line.

But concretely, that why you can’t currently do def foo {1} and have it do what you want: it already means something different…

the = makes complete sense.

given x=1, y=1

val a = x+y //tell the compiler(or reader of the code) that a is constant value and is to be replaced with x+y=2, everywhere

var a = x+y //tell the compiler that a is a variable and is to be replaced with x+y=2 or its changed value if a was reassigned with another value

def a = x+y //tell the compiler that a is a method(one could argue “func” is a better name) and is to be replaced with expression x+y which is to be calculated everytime it is used

the = makes the val, var, def consistent and very simple to understand.

1 Like

Thank you for your reply.
Is he not here?
I am glad if there is a link etc.

I did not know that scalars can be written as def foo{1}.

The right hand side of the equals is always a single expression (In the scala world these are called terms and also include a few other constructs such as if statements). A block is an expression that contains multiple lines, and returns the last line as it’s result (ignoring the return keyword semantics). So def foo = {1} is actually a Block with the number “1” inside it.

The other way of writing things is called “procedure syntax” and as far as I’m aware it’s not in Dotty (aka Scala 3). Procedure syntax was added to scala for similarity to java.

One reason the equals is there is that EVERY scala method/function returns a result, unlike java. Scala unit and java’s void are not the same thing. Void methods in java are called subroutines and do not return anything at all (technically scala does not have subroutines)

You can also assign a def to a constant like

def a = 1 Without any brackets at all.

1 Like