在Scala中,可以在其他方法中定义方法.这将它们的使用范围限制在定义块内.我使用它们来提高使用几个高阶函数的代码的可读性.与匿名函数文字相比,这允许我在传递它们之前给它们有意义的名称.
例如:
class AggregatedPerson extends HashSet[PersonRecord] {
def mostFrequentName: String = {
type NameCount = (String, Int)
def moreFirst(a: NameCount, b: NameCount) = a._2 > b._2
def countOccurrences(nameGroup: (String, List[PersonRecord])) =
(nameGroup._1, nameGroup._2.size)
iterator.toList.groupBy(_.fullName).
map(countOccurrences).iterator.toList.
sortWith(moreFirst).head._1
}
}
Run Code Online (Sandbox Code Playgroud)
是否有任何运行时成本,因为我应该知道嵌套方法定义?
关闭的答案有何不同?