Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: How to "store" a function in a var?

I'm learning Scala and I'm trying to store a function in a var to evaluate it later:

var action:() => Any = () => {}
def setAction(act: => Any) {
    action = act 
}

but that doesn't compile:

error: type mismatch;
found: Any
required: () => Any
action = act

So it seems to me that in action = act instead of assigning the function it's evaluating it and assigning the result.
I can´t find out how to assign the function without evaluating it.

Thanks!

like image 766
Damian Avatar asked Oct 23 '09 03:10

Damian


People also ask

Can you store a function as a variable?

Functions stored in variables do not need function names. They are always invoked (called) using the variable name. The function above ends with a semicolon because it is a part of an executable statement.

How do you use function as a variable in Scala and what is the usage?

Use def to define a method, val to create a function. When assigning a function to a variable, a function literal is the code on the right side of the expression. A function value is an object, and extends the FunctionN traits in the main scala package, such as Function0 for a function that takes no parameters.

What is the meaning of => in Scala?

=> is syntactic sugar for creating instances of functions. Recall that every function in scala is an instance of a class. For example, the type Int => String , is equivalent to the type Function1[Int,String] i.e. a function that takes an argument of type Int and returns a String .


2 Answers

Note type "() => Any" is not the same as by-name parameter "=> Any". Type "() => Any" is a function that takes no parameter and returns Any, whereas by-name parameter "=> Any" delays execution of the parameter until it's used and returns Any.

So what you need to do here is the following:

var action: () => Any = null

def setAction(act: => Any) = action = () => act

setAction(println("hello")) // does not print anything

action() // prints "hello"

setAction(123)

action() // returns 123
like image 116
Walter Chang Avatar answered Sep 28 '22 02:09

Walter Chang


I think you're parameter declaration is wrong. This is probably what you want if you simply want to store a function in a var for later use:

def setAction(act:() => Any) {
    action = act 
}

and then:

scala> def p() { println("hi!") }
p: ()Unit

scala> setAction(p)

scala> action()
hi!
res2: Any = ()
like image 23
Dave Ray Avatar answered Sep 28 '22 00:09

Dave Ray