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 ?
def is the keyword you use to define a method, the method name is double , and the input parameter a has the type Int , which is Scala's integer data type. The body of the function is shown on the right side, and in this example it simply doubles the value of the input parameter a : def double(a: Int) = a * 2 -----
In scala, functions are first class values. You can store function value, pass function as an argument and return function as a value from other function. You can create function by using def keyword. You must mention return type of parameters while defining function and return type of a function is optional.
=> is the "function arrow". It is used both in function type signatures as well as anonymous function terms. () => Unit is a shorthand for Function0[Unit] , which is the type of functions which take no arguments and return nothing useful (like void in other languages).
A method is a function defined in a class and available from any instance of the class. The standard way to invoke methods in Scala (as in Java and Ruby) is with infix dot notation, where the method name is prefixed by the name of its instance and the dot ( . )
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With