0

I am new to scala, today I saw a function definition I could not understand:

def f(x: Int): Int = x
val func = (x: Int, y: Int, z: Int) => f(x)

So in Scala, what is the syntax of defining func ? To me, func is just a function accepts three parameters: func: (Int, Int, Int) => Int = <function3> . Why not just define func as

def func(x: Int, y: Int, z: Int): Int = f(x)

Is this for the reason of efficiency ? Since we just need to evaluate a val once.

user2018791
  • 1,143
  • 15
  • 29
  • http://stackoverflow.com/questions/18887264/what-is-the-difference-between-def-and-val-to-define-a-function See the last paragraph of the accepted response. – vptheron Sep 03 '14 at 14:35

1 Answers1

-1

func is defined as a value that holds a function with that signature, and it is initialized with such a function. At some time in the future, in a class method, you could provide a different function. It would be invoked as func(1,2,3) and return the result based on the function that was actually assigned to func at that point in time.

This provides an alternative to overriding a method in a subclass. For instance, you might have a state machine implementation that needed to respond to inputs in a different fashion, depending upon the state; this would be feasible way to respond appropriately by changing the value of the receiving function.

Bob Dalgleish
  • 8,167
  • 4
  • 32
  • 42