Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between these three ways of defining a function in Scala

Tags:

scala

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> 
like image 349
qrest Avatar asked Sep 05 '10 16:09

qrest


People also ask

What is the difference between method and function in Scala?

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.

What is the difference between DEF and Val in Scala?

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.

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

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) 
like image 179
Jack Avatar answered Sep 18 '22 13:09

Jack