Damian
Damian

Reputation: 5561

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!

Upvotes: 8

Views: 5296

Answers (2)

Dave Ray
Dave Ray

Reputation: 40005

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 = ()

Upvotes: 2

Walter Chang
Walter Chang

Reputation: 11596

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

Upvotes: 15

Related Questions