Any ...">

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

I am learning Scala and I am trying to save a function in var to evaluate it later:

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

but this does not compile:

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

So it seems to me that in action = act instead of assigning a function, it evaluates it and assigns the result.
I cannot learn how to assign a function without evaluating it.

Thanks!

+7
scala anonymous-function
source share
2 answers

The record type "() => Any" is not the same as the "by name" => "Any" parameter. The type "() => Any" is a function that takes no parameter and returns Any, while the by-name parameter "=> Any" delays the execution of the parameter before using it and returns Any.

So you need to do 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 
+15
source share

I think the parameter declaration is incorrect. This is probably exactly what you want if you just want to save the function in 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 = () 
+2
source share

All Articles