The cost of nested methods

Posted by Palimondo on Stack Overflow See other posts from Stack Overflow or by Palimondo
Published on 2010-03-20T07:38:39Z Indexed on 2010/03/20 7:41 UTC
Read the original article Hit count: 313

Filed under:
|

In Scala one might define methods inside other methods. This limits their scope of use to inside of definition block. I use them to improve readability of code that uses several higher-order functions. In contrast to anonymous function literals, this allows me to give them meaningful names before passing them on.

For example:

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
  }
}

Is there any runtime cost because of the nested method definition I should be aware of?

Does the answer differ for closures?

© Stack Overflow or respective owner

Related posts about scala

Related posts about method