0

Is def x = 1 a function or a variable declaration? And, what is the difference between:

def x = 1 // REPL x: Int
def x() = 1 // REPL x: () Int

Looks like the first one is a variable definition. Please clarify.

Huang Chen
  • 1,177
  • 9
  • 24
BestCoderEver
  • 467
  • 1
  • 7
  • 15

1 Answers1

2

No difference at all. Braces are optional for methods with no arguments in Scala. It is a convention to use them, if the method modifies any kind of state, and to leave the away, if it does not (at the call site too).

Both are method definitions. var x = 1 or val x = 1 would be variable definitions.

midor
  • 5,487
  • 2
  • 23
  • 52
  • One minor nuance, the def statements actually define methods rather than functions. There are some under the hood differences between the two. Functions in Scala are classes with an apply method as opposed to methods which are just plain old methods. One consequence of this, for example, is that functions can't be overloaded. Here is a solid write up - https://tpolecat.github.io/2014/06/09/methods-functions.html – DemetriKots Jul 29 '15 at 17:58