我目前正在学习Scala,但仍有很多事情我不明白......
所以,当出现一个疯狂的答案时,我随机浏览了一些堆栈溢出:https://stackoverflow.com/a/19093282/3529754
这个答案使用了一个隐含参数,而foldLeft函数则使用了 - 是的,看起来像是一个 - 日本笑脸。问题的源代码:
class Account(implicit transactionLog: TransactionLog) {
def balance = transactionLog.foldLeft(_ + _)
}
class TransactionSlip(from: Account, to: Account, amount: BigDecimal)
在这种情况下,隐含关键字到底意味着什么?笑脸有什么作用?我只是不能从周围的片段中得到它......
先谢谢。
答案 0 :(得分:4)
两个答案:
_ + _
是placeholder for the function that takes two arguments and adds them。下划线是用这种语法标记参数的位置。您可以阅读this了解Scala中下划线的所有用法。
implicit
关键字表示implicit argument。这意味着在需要Account
的地方,可以使用构造函数提供一个,而不显式提供相应的transactionLog
,这将从上下文中获取。