Given three ways of expressing the same function f(a) := a + 1
:
val f1 = (a:Int) => a + 1 def f2 = (a:Int) => a + 1 def f3:(Int => Int) = a => a + 1
How do these definitions differ? The REPL does not indicate any obvious differences:
scala> f1 res38: (Int) => Int = <function1> scala> f2 res39: (Int) => Int = <function1> scala> f3 res40: (Int) => Int = <function1>
Scala functions are first class values. Difference between Scala Functions & Methods: Function is a object which can be stored in a variable. But a method always belongs to a class which has a name, signature bytecode etc. Basically, you can say a method is a function which is a member of some object.
That's all about the difference between var, val, and def in Scala. In short, the val and var are evaluated when defined, while def is evaluated on call. Also, val defines a constant, a fixed value that cannot be modified once declared and assigned while var defines a variable, which can be modified or reassigned.
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.
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 ( . )
Inside a class, val
is evaluated on initialization while def
is evaluated only when, and every time, the function is called. In the code below you will see that x is evaluated the first time the object is used, but not again when the x member is accessed. In contrast, y is not evaluated when the object is instantiated, but is evaluated every time the member is accessed.
class A(a: Int) { val x = { println("x is set to something"); a } def y = { println("y is set to something"); a } } // Prints: x is set to something val a = new A(1) // Prints: "1" println(a.x) // Prints: "1" println(a.x) // Prints: "y is set to something" and "1" println(a.y) // Prints: "y is set to something" and "1" println(a.y)
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