【发布时间】:2014-11-07 19:38:12
【问题描述】:
我想在我的 Scala 代码中实现动作链。我想我可以为此使用“折叠”。所以,假设我有这样声明的动作序列:
val chainOfActions: Seq[String => String] = Seq(
{resultFromPreviousAction =>
println("Inside the first action")
"Result from the first action"
},
{resultFromPreviousAction =>
println("Inside the second action")
resultFromPreviousAction + " > " + "Result from the second action"
}
)
上面的代码可以编译(我在 scala 控制台中尝试过)。
接下来是应用折叠:
chainOfActions.fold("") { (intermediateText, action) =>
action(intermediateText)
}
但上面的代码给出了以下错误:
<console>:10: error: Object does not take parameters
action(intermediateText)
嗯...为什么我的动作失去了它的类型(我期望类型是“String => String”)?
所以我尝试声明类型:
type MyBlockType = String => String
并以这种方式声明我的 Seq:
val chainOfActions: Seq[MyBlockType] = Seq(
{resultFromPreviousAction =>
println("Inside the first action")
"Result from the first action"
},
{resultFromPreviousAction =>
println("Inside the second action")
resultFromPreviousAction + " > " + "Result from the second action"
}
)
仍然出现同样的错误。所以,我试图检查“动作”的实际类型......:
chainOfActions.fold("") { (intermediateText, action) =>
println(action.getClass)
"Test it"
}
我在控制台中得到了这个信息:
class $line101.$read$$iw$$iw$$anonfun$1
class $line101.$read$$iw$$iw$$anonfun$2
res58: Object = Test it
所以...,它是正确的(它是一个函数)。但是为什么 Scala 不将其识别为对象呢?
请帮我指出我哪里做错了。
谢谢, 拉卡
【问题讨论】:
标签: scala functional-programming fold method-chaining