0

Is the reason a val variable can be used to contain a function definition is because functions are first class citizens where they can be contained in variables?

VividMan
  • 1
  • 3
  • 1
    `(x: Int) => x + 1` can be assigned to a variable, for similar reasons `42` can be assigned to a variable. – Mario Galic Jun 05 '20 at 20:49
  • 1
    See https://stackoverflow.com/questions/18887264/what-is-the-difference-between-def-and-val-to-define-a-function – user Jun 05 '20 at 20:49
  • 1
    _"because functions are first class citizens where they can be contained in variables"_ yes, you answered yourself. BTW, you may also want to read this: https://stackoverflow.com/questions/2529184/difference-between-method-and-function-in-scala – Luis Miguel Mejía Suárez Jun 05 '20 at 21:00

1 Answers1

2

In Scala damn near everything is an expression. From a practical perspective what that means is pretty much every bit of syntactically correct Scala code that you can write evaluates to an object that can you can do more Scala on. Examples of things you can do to these objects are: call a method on it, pass it to a function, or store it in a val. Expressions can be thought of in contrast to statements, which are just instructions to the computer to do something. An example of the use of statements in Scala are import commands. The heavy prevalence of expressions in Scala are a deliberate design choice intended to make the language more flexible and extensible.

mdornfe1
  • 1,982
  • 1
  • 24
  • 42