Why are `def aPlusOne = a + 1` and `val aPlusOne = () => a + 1` different in Scala?

Viewed 72

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?

1 Answers
scala> var a = 4 //mutable variable (bad, bad, bad)
a: Int = 4

scala> def aPlusOne = a + 1  //a method
aPlusOne: Int

scala> val f = aPlusOne _  //a function via eta-expansion
f: () => Int = $$Lambda$1762/0x0000000840820840@7e3f9be9

scala> f()  //invoke function
res1: Int = 5

scala> a = 2  //reset a
a: Int = 2

scala> f()  //yep, it works
res2: Int = 3

The difference between method and function? You're not the first to ask.

Related