2

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?

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
zeejan
  • 265
  • 1
  • 4
  • 10
  • 1
    Why not just using `aPlusOne`? Anyways, `aPlusOne` is a **method**, so if you want to store its computation rather than its result, you have to transform it into a **function**, you can do it in many ways, 1) A explicit lambda `val fun = (x: Int) => aPlusOne(x)` 2) explicit _eta-expansion_ `val fun = aPlusOne _` 3) implicit _eta-expansion_ `val fun: Int => Int = aPlusOne` – Luis Miguel Mejía Suárez Aug 31 '20 at 03:26
  • I was reading the book Programming in Scala. It mentions that for Postfix Operators we can ignore the `()` if there is no side effect like `s toLowerCase`. This raises my question about the difference between `calling the function` and `saving the function in a variable`. In many other languages, binding/assigning a function name without `()` means taking the function as a value. – zeejan Aug 31 '20 at 03:47
  • 1
    Both, postfix operators and removing `()` are discouraged and deprecated. – Luis Miguel Mejía Suárez Aug 31 '20 at 04:55

1 Answers1

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

jwvh
  • 50,871
  • 7
  • 38
  • 64