Scala3 - Do we still need the def keyword for declaring methods, if so - why?

$subject

Because without def language would be ambiguous?

abstract class ClassA {
  def method(): Unit // declare abstract method
  method(): Unit // invoke method
}

What about

abstract method(): R

…for abstract declarations, and

method(): R = {
  // stuffaroo
}

for definitions?

IMO it’s clearer with an abstract marker than defs “all over the place”.

method() = {
}

is valid syntax, and desugars to

method().update({

})

Ok, I give up:-)

In a language where you have a clearly separate scope between declaration and definition, it comes easier, since you only declare functions at top level and only call them in other functions’ definition.

Scala has different scopes where you both can define and call, and the confusion is hard to avoid…

Additionally in scala you have many definitions with different semantics (def, val, var, lazy val), therefore having a keyword is more regular across the language. And the regularity extends to the call site, abiding the so-called universal-access-principle.
The alternative would significantly differentiate methods’ definition from the rest of declarations.

It might be worth investigating, but I see no terribly good reason and gains from changing the current situation. Do you have any to suggest?

1 Like