This page is no longer maintained — Please continue to the home page at

"Private" method parameters for recursive methods

No replies
Luigi Plinge
Joined: 2011-04-01,
User offline. Last seen 1 year 19 weeks ago.
Hi, I'm new to the mailing list so sorry if this has been discussed before, or indeed if it's already possible. I searched but didn't find anything.

I really like the default parameters that you can put in methods, and they're very useful for making tail recursive methods more concise and legible. For instance, if we take a regular recursive method for list length
def length(list: List[Any]): Int = list match {
  case head :: tail => 1 + length(tail)
  case Nil => 0

it grows when we try to make it tail-recursive
def length(list: List[Any]): Int = { def lengthrec(list: List[Any], result: Int): Int = list match { case head :: tail => lengthrec(tail, result + 1) case Nil => result } lengthrec(list, 0) }
but this can be nicely cut down with a default parameter:

def length(list: List[Any], result: Int = 0): Int = list match {
case head :: tail => length(tail, result + 1)
case Nil => result
The problem now is that although we can still call it in the same way (length(List(1,2,3,4))), we've exposed the result parameter, which we probably don't want. The only time we want this to be visible is within the scope of the method itself.

Would it therefore be possible or desirable to introduce an optional access modifier that could be used to make recursive methods much easier and cleaner to write?

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland