How do I assign a function to a value in Scala?

In Scala, how do you assign a specific signature function to the corresponding typed value?

def foo = println("foo")
def bar = println("bar")
val fnRef : ()=>Unit = //the function named foo or the function named bar

      

+1


source to share


2 answers


While I feel like an unforgivable-horrible person to present this as an official answer, I am doing this as requested by the OP.

This problem can be solved like this:

def foo = println("foo")
val fnRef = () => foo

      



or, as some other brave soul said, before deleting his answer:

def foo = println("foo")
val fnRef = foo _

      

The second is perhaps a little preferable since mine (the first) is a bit hackish and actually creates a completely new function that just calls an existing function when it is applied, whereas the latter is mostly a partial or deferred application of an existing function , because being semantically identical, the latter is more-idiomatic Scala (as Rex Kerr points out).

+2


source


foo

and bar

are not functions, they are methods. You cannot assign methods to a name, because methods are not objects.



0


source







All Articles