Reputation: 13700
I am new to scala, but I have background in javascript.
While I see the need to separate between val
and var
(mutable and immutable), I can't see why the def
statement should ever be needed.
If functions are truly first-class citizens, as in javascript, why should they be declared with def
and not with val
?
Is that design decision based on JVM related constraints, or is there some underlying logic that I fail to comprehend ?
Upvotes: 6
Views: 148
Reputation: 67290
One big limitation of functions is that they cannot be generic as a value. E.g.
def foo[A](bar: A): Unit
That cannot be expressed as a function value
val foo: A => Unit // A is _not_ a type parameter
that requires a resolution of type parameter A
. Other differences are: Methods carry a natural notion of this
as the enclosing class; they can abort via return
. They can have multiple parameter lists, most importantly an implicit parameter list. They have named and default arguments. (I'm trying to imagine how a function with named and default arguments would look, perhaps it could be designed)
It probably would not have been impossible to just have function values, but def
seems like a better match for the OO aspects of Scala.
Upvotes: 9
Reputation: 79521
def
differs from val
and var
in that every time the variable is referenced, its expression is reevaluated.
Upvotes: 4
Reputation: 9734
I think it's language decision made for easier migration from Java. It's quite a big shift in mind to watch on functions as on function-values.
Upvotes: 1