Reputation: 4992
I have the following code in Scala-IDE:
type myF = () => Boolean
def acceptFunction(f: myF) {
//...
}
and then:
var a = false
def isA = () => a
but when I try passing it, to the acceptFunction, it results in error:
acceptFunction(isA)
the error is:
type mismatch; found : () => Boolean required: Boolean
But why?
If I declare isA
like this:
def isA() = () => a
then it is accepted, but I assume, it get's evaluated because of the parenthesis.
Is there any way to pass such a function for furhter evaluation?
UPDATE:
Looks like it is something with Scala-IDE. The REPL has no problems with these expressions. However, still I can't make it so that the passed function does not get turned into a closure. I mean, that it turns into closure, and changing the var a
later and calling the example with println(f())
again - does not change the value. So, the second part of the question remains - is there any way to pass such a function for furhter evaluation?
Upvotes: 0
Views: 549
Reputation: 3724
Are you sure you didn't make a mistake when writing your code the first time? I copied and pasted what you had into the 2.9.1 REPL and it worked fine.
scala> type myF = () => Boolean
defined type alias myF
scala> var a = false
a: Boolean = false
scala> def isA = () => a
isA: () => Boolean
scala> def acceptFunction(f: myF) {println(f())}
acceptFunction: (f: () => Boolean)Unit
scala> acceptFunction(isA)
false
scala>
UPDATE: isA
is a closure when you define it. Passing it to acceptFunction
has no effect on whether it grabs a
.
Is your purpose to write a function, acceptFunction
, which takes a function, f
, which captures an external value, a
, at the time it's defined?
You could do that like so:
// Defines a function which returns a function with returns the
// value that was captured at the outer function's call time.
def isB = { (b: Boolean) => { () => b }: myF }
a = true
val f = isB(a)
acceptFunction(f) // >> true
a = false
acceptFunction(f) // >> true
Is that where you're trying to go?
Upvotes: 1