Scala lists "var" usage

Viewed 58

I am still relatively very new to Scala. I was going through the List implementation of Scala, where I saw that a lot of funcitons still use "var" in the implementation. I have been reading how scala is more functional oriented, therefore instead of using "var" should the library not use tail recursion where possible.

For example exsits could be re-written as:

@tailrec
def exists[A](f : A => Boolean) : Boolean = this match {
    case Nil => false
    case l:LinearSeq[A]=> if (f(l.head)) true else exists(l.tail,f)
}

The reason I ask is as I have being reading a lot of material where it is discouraged to use "var", but I see a lot of that being used in the List implementation.

Thanks!

3 Answers

When you have something like List, which is used very often in nearly every Scala program:

  1. even a very minor speedup (or slowdown) can have a large cumulative effect;

  2. its contributors tend to be ones who know a lot about Scala low-level details (and if some don't, their patches will be reviewed by those who do).

So advice given to people just learning Scala isn't particularly applicable.

For this specific example: @tailrec didn't exist until Scala 2.8, this code was probably written earlier (I haven't checked) and there is not sufficiently good reason to rewrite it.

The designers of the standard library chose performance over purity.

The main downside is that the standard library is not a good resource for learning about how to write pure functional code.

A secondary downside is that it reduces the incentive for the compiler to optimise pure functional code, because it does not affect the core library.

The blunt reason is usually performance. With the reasoning that local (!) vars do not break FP and still allow concurrency to work.

In this case, the reason probably is another. The implementation works also for non-Lists, only using the IterableOnce methods.

Related