【发布时间】:2017-10-17 09:52:12
【问题描述】:
我有这种方法,给定一系列工具,它会查询 Web 服务以获取旧价格和新价格。然后它将使用一个函数来查看价格差异是否显着。它将返回第一个具有显着价格差异的工具。 现在,我的问题是它总是返回 None ,除非我添加如下明确的 return 语句。
我了解 scala 返回要评估的最后一个表达式。有没有办法重构此代码以避免显式返回。
在什么情况下我们不能避免显式的返回语句?
// without explicit return
def findEquty[A](instruments: Seq[A], change: (Double, Double) => Boolean): Option[A] = {
for (instrument <- instruments) {
val oldPrice = getOldPrice(instrument)
val newPrice = getNewPrice(instrument)
if (change(oldPrice, newPrice)) Some(instrument)
}
None
}
// with explicit return
def findEquty[A](instruments: Seq[A], change: (Double, Double) => Boolean): Option[A] = {
for (instrument <- instruments) {
val oldPrice = getOldPrice(instrument)
val newPrice = getNewPrice(instrument)
if (change(oldPrice, newPrice)) return Some(instrument)
}
None
}
【问题讨论】:
标签: scala