Cory Klein
Cory Klein

Reputation: 55620

Assign an existing function to a val?

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?

Upvotes: 3

Views: 79

Answers (1)

stew
stew

Reputation: 11366

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

Upvotes: 9

Related Questions