Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Scala need the def statement?

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 ?

like image 816
Uri Goren Avatar asked Oct 14 '14 20:10

Uri Goren


People also ask

What is a Def in Scala?

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 -----

How do you define a function in Scala?

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.

What does => mean in Scala?

=> 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).

What do you call a function defined in a block in Scala?

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 ( . )


1 Answers

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.

like image 185
0__ Avatar answered Sep 18 '22 10:09

0__