As most of us know , stacks will be used to evaluate function calls. I am aware of the following code how it works in terms of closure etc … However, I could not correlate in terms if internals ( how stack will be used to evaluate the following )
How exactly stack will look like when each of the following line executed ?
def mulBy(factor : Double) = (x : Double) => factor * x
val quintuple = mulBy(5)
quintuple(20) // 100
Nothing fancy, just something like this:
- Call quintuple.apply(20)
- Call 20 * 5
- Result
And quintuple was created by calling mulBy
which is just a simple method call (just one stack frame) that returned a simple value, the function.
Can you elaborate further with more details ?
I assume the following code will create a function variable which is yet to be executed ?
def mulBy(factor : Double) = (x : Double) => factor * x
Will it be part of the stack or stored as simple variable ?
What about other lines ?
def mulBy(factor : Double) = (x : Double) => factor * x
Defines a method.
At runtime, this line technically is not executed.
val quintuple = mulBy(5)
- Call the
mulBy
method - 1 stack frames.
- Call the constructor of Function1 (this is actually more complex internally, but you shouldn’t care about that) - 2 stack frames.
- Return from the constructor - 1 stack frames.
- Return from the
mulBy
method - 0 stack frames.
quintuple(20)
- Call the
apply
method on quintuple - 1 stack frames.
- Call the
*
method on 5 - 2 stack frames.
- Does the multiplication - 2 stack frames.
- Return from the
*
method - 1 stack frames.
- Return from the
apply
method - 0 stack frames.