如何提供命名函数来映射没有lambdas

Dom*_*kis 0 lambda scala future anonymous-function

我想Future通过使用较少的lambda 来使我的用法更具建设性.目前我正在使用map和lambdas来访问期货的结果.例如:

val rateQuote = future {
  connection.getCurrentValue(USD)
}
val purchase = rateQuote map { quote =>  
  if (isProfitable(quote)) connection.buy(amount, quote)
  else throw new Exception("not profitable")
}
purchase onSuccess {
  case _ => println("Purchased " + amount + " USD")
}
Run Code Online (Sandbox Code Playgroud)

map我不想为每个提供lambda(匿名函数),而是提供一个命名函数/方法.我该怎么办?例如:

val rateQuote = future {
  connection.getCurrentValue(USD)
}
def namedFunction(arg: Arg) = 
  if (isProfitable(quote)) connection.buy(amount, quote)
  else throw new Exception("not profitable")

val purchase = rateQuote map { quote => namedFunction }
Run Code Online (Sandbox Code Playgroud)

甚至更好

val purchase = rateQuote map namedFunction
Run Code Online (Sandbox Code Playgroud)

我主要担心的是,我发现自己将太多的逻辑移动到lambda中,调试比命名函数更难.

om-*_*nom 6

如果我找对你,那就不应该困难了:

def buyIfProfitable(quote: Quote) = 
  if (isProfitable(quote)) connection.buy(amount, quote)
  else throw new Exception("not profitable")

val purchase = rateQuote.map(q => buyIfProfitable(q))
Run Code Online (Sandbox Code Playgroud)

或者干脆

val purchase = rateQuote.map(buyIfProfitable)
Run Code Online (Sandbox Code Playgroud)