【发布时间】:2011-09-08 07:10:22
【问题描述】:
我有一个贷款模式,它应用一个函数 n 次,其中“i”是递增变量。 “偶尔”,我希望传入的函数能够访问'i'......但我不想要求传入的所有函数都需要定义一个参数来接受'i'。下面的例子...
def withLoaner = (n:Int) => (op:(Int) => String) => {
val result = for(i <- 1 to n) yield op(i)
result.mkString("\n")
}
def bob = (x:Int) => "bob" // don't need access to i. is there a way use () => "bob" instead?
def nums = (x:Int) => x.toString // needs access to i, define i as an input param
println(withLoaner(3)(bob))
println(withLoaner(3)(nums))
【问题讨论】:
-
与问题无关,但如果你写 def f : (args) => expr 而不是 def f(args) = expr (我不确定我一般会这样做),你可以让 f 成为 val 而不是 def。
标签: scala