3

The Scala front page says

Functions are first-class objects. Compose them with guaranteed type safety. Use them anywhere, pass them to anything.

But I can't seem to store a function in a val like I would with other first-class objects in Scala.

scala> def myFunction = { println("hello world") }
myMethod: Unit

scala> myFunction
hello world

scala> val myVal = myFunction
hello world
myVal: Unit = ()

scala> myVal

scala>

What is the right way to do this?

Cory Klein
  • 51,188
  • 43
  • 183
  • 243

1 Answers1

9

So, functions are first class values, however, def creates a method, not a function. You can turn any method into a function using "eta-expansion" by appending a _ to the method name:

scala> def myFunction = { println("hello world") }
myFunction: Unit

scala> myFunction _
res0: () => Unit = <function0>

scala> res0()
hello world

scala> val myVal = myFunction _
myVal: () => Unit = <function0>

scala> myVal
res2: () => Unit = <function0>

scala> myVal()
hello world
stew
  • 11,276
  • 36
  • 49