1

Scala allows functions with no parameter lists to be invoked without parentheses:

scala> def theAnswer() = 42
theAnswer: ()Int

scala> theAnswer
res5: Int = 42

How would I construct a scala expression that evaluates to the function theAnswer itself, rather than the result of theAnswer? Or in other words, how would I modify the expression theAnswer, so that the result was of type () => Int, and not type Int?

Asad Saeeduddin
  • 46,193
  • 6
  • 90
  • 139

2 Answers2

6

It can be done with:

scala> theAnswer _
res0: () => Int = <function0>

From the answer to the similar question:

The rule is actually simple: you have to write the _ whenever the compiler is not explicitly expecting a Function object.

This call will create the new instance every time, because you're "converting" method to function (what is called "ETA expansion").

Community
  • 1
  • 1
Dmitry Ginzburg
  • 7,391
  • 2
  • 37
  • 48
  • Does this create a new function object? E.g. if I do `val f: () => Int = theAnswer; f == f` I get true, however if I do `(theAnswer _) == (theAnswer _)` I get false. If I'm not mistaken this seems to indicate you're wrapping `theAnswer` into another function when you do `theAnswer _` – Asad Saeeduddin Aug 05 '15 at 13:41
  • @Asad see the updated answer, of couse, you'll get false if you create the new instance. – Dmitry Ginzburg Aug 05 '15 at 13:45
  • I see. I'm looking for a way to get a reference to the actual function, not create another function that delegates to the first one. So I guess the answer to that question is, "the question is malformed, methods are not functions". – Asad Saeeduddin Aug 05 '15 at 13:48
  • @Asad You're right and methods are not functions. In fact, the methods in Scala are Java methods, which cannot be referenced as variables, like functions do. – Dmitry Ginzburg Aug 05 '15 at 13:58
3

Simply:

scala> val f = () => theAnswer
f: () => Int = <function0>

scala> val g = theAnswer _
g: () => Int = <function0>
Jean Logeart
  • 52,687
  • 11
  • 83
  • 118