Why does Scala need a def statement?

I am new to scala, but I have background in javascript.

While I see the need for a separation between val and var (mutable and immutable), I cannot understand why the def statement will ever be needed.

If functions are really first-class citizens, as in javascript, why should they be declared with def and not with val ?

Is this a constructive solution based on the constraints associated with the JVM, or is there some kind of basic logic that I don't understand?

+6
source share
3 answers

One big limitation of functions is that they cannot be universal in value. For instance.

 def foo[A](bar: A): Unit 

This cannot be expressed as a function value.

 val foo: A => Unit // A is _not_ a type parameter 

for which type A parameter resolution is required. Other differences: methods carry the natural concept of this as an encompassing class; they can be interrupted by return . They can have several parameter lists, and most importantly, a list of implicit parameters. They have default names and arguments. (I'm trying to imagine what a function with named and standard arguments will look like, maybe it can be developed)

It would probably not be possible to simply have function values, but def seems to be the best match for the OO Scala aspects.

+9
source

def differs from val and var in that each time it refers to a variable, its expression is reevaluated.

+4
source

I think this is a solution in the language that facilitates the transition from Java. This is a pretty big shift in mind to look at functions as functional values.

+1
source

Source: https://habr.com/ru/post/976743/


All Articles