I wish to save a function in a name and evaluate it anytime I need. In JavaScript it could be something like this without using anonymous functions.
let a = 5
function aPlusOne() {
return a + 1
}
let func = aPlusOne
a = 6
result = func() // which gives us 7
My question is how to do it in Scala?
scala> var a = 7
scala> def aPlusOne = a + 1
aPlusOne: Int
scala> var myFunc2 = aPlusOne
myFunc2: Int = 8 // OK, 7 + 1
scala> myFunc2
res3: Int = 8
scala> a = 9
a: Int = 9
scala> myFunc2
res4: Int = 8 // shall be 9 + 1 = 10
The second time we call myFunc2
, it returns 8 not 9 + 1 which is 10. So it was evaluated when we created it.
I wonder if there is a way to save just the function not the evaluated value.
If it is not clear, I want to do something like this without using Lambda
scala> val myLambda = () => a + 1
myLambda: () => Int = <function0>
scala> myLambda()
res2: Int = 8
scala> a = 9
a: Int = 9
scala> myLambda()
res3: Int = 10
Or to say
What's the difference between def aPlusOne = a + 1
and val aPlusOne = () => a + 1
? And why is there a difference, since in other languages they could be used the same way as a function?