0

Scala-IDEには次のコードがあります。

type myF = () => Boolean

def acceptFunction(f: myF) {
  //...
}

その後:

var a = false

def isA = () => a

しかし、それをacceptFunctionに渡そうとすると、エラーが発生します。

acceptFunction(isA)

エラーは次のとおりです。

型の不一致; 見つかった:()=>必要なブール値:ブール値

しかし、なぜ?

私がこのように宣言した場合isA

def isA() = () => a

その後、受け入れられますが、括弧のために評価されると思います。

さらに評価するためにそのような関数を渡す方法はありますか?

アップデート:

Scala-IDEを使ったもののようです。REPLはこれらの式に問題はありません。ただし、渡された関数がクロージャにならないようにすることはできません。つまり、クロージャになり、var a後で変更して例をprintln(f())再度呼び出すと、値は変更されません。したがって、質問の2番目の部分は残ります-さらに評価するためにそのような関数を渡す方法はありますか?

4

1 に答える 1

1

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?

于 2012-04-11T14:40:24.640 に答える