Mandroid
Mandroid

Reputation: 7478

Scala: List.forall using while loop

I see following implementation in List.scala from Scala library:

override final def forall(p: A => Boolean): Boolean = {
    var these: List[A] = this
    while (!these.isEmpty) {
      if (!p(these.head)) return false
      these = these.tail
    }
    true
  }

This method can be implemented recursively to get rid of var and while loop. Reading through all available books,blogs, articles etc online etc, I am under impression that we are supposed to follow recursive approach as much as we can in Scala.

Upvotes: 1

Views: 76

Answers (2)

Mario Galic
Mario Galic

Reputation: 48410

The mutability of var these is not visible outside forall method and likely helps with performance

override final def forall(p: A => Boolean): Boolean = {
  var these: List[A] = this
  ...
  true
} // var is out-of-scope at this point

so technically forall is still pure from perspective of callers. Tail recursive approach would also probably have similar performance as var+while though.

Upvotes: 2

Bondarenko
Bondarenko

Reputation: 293

The recursive approach is considered more declarative and readable that's why it's a good approach. From the other side functional approach implies immutibilty in particular which can lead to perfornace degradation so using such approach in Scala library is understandable. I assume that the authors of the Scala library didn't assume users heavily read their code as it's should be under the hood.

Upvotes: 0

Related Questions