1

Why does f in the following code snippet gives the value of 1. I was expected f() to be 1. How can I obtain a reference to the function f:()=> Int

var y = 0
def f():Int = {y + 1}

f

Somethings in scala drive me nuts.

Rpant
  • 974
  • 2
  • 14
  • 37
  • `f` returns `Int` as per your definition – Raj Dec 04 '18 at 23:32
  • 3
    One of the many [differences between methods and functions](https://stackoverflow.com/questions/2529184/difference-between-method-and-function-in-scala). – jwvh Dec 05 '18 at 00:33
  • You cannot obtain a reference to the function `f`, because there is no function `f` in your code. There is only a method `f`, which is something completely different. – Jörg W Mittag Dec 08 '18 at 07:31

3 Answers3

5

If you're calling a function that has no parameters, then you can drop the brackets. That's why f evaluates to 1.

The exact same expression can also evaluate into a function reference if the compiler knows that you're expecting a value of that type.

val foo: () => Int = f
Aki
  • 1,644
  • 12
  • 24
3

You can obtain so using _ :

  var y = 0
  def m:Int = {y + 1}
  val result = m _  // type of result is an instance of Function0 "() => Int"

Use _ when compiler is not expecting Function object.

Rpant
  • 974
  • 2
  • 14
  • 37
mukesh210
  • 2,792
  • 2
  • 19
  • 41
2

If you want f to be an expression of type () => Int that evaluates to { y + 1 }, then just define it as such:

var y = 0
val f: () => Int = () => { y + 1 }

Now

f

does nothing (it just gives back the lambda of type () => Int), but

f()

gives 1.

You don't really need the type ascription, this works too:

val f = () => { y + 1 }
Andrey Tyukin
  • 43,673
  • 4
  • 57
  • 93