Is Scala idiomatic coding style just a cool trap for writing inefficient code?

后端 未结 10 742
借酒劲吻你
借酒劲吻你 2020-12-22 17:19

I sense that the Scala community has a little big obsession with writing \"concise\", \"cool\", \"scala idiomatic\", \"one-liner\" -if possible- code. This

10条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-22 17:27

    For reference, here's how splitAt is defined in TraversableLike in the Scala standard library,

    def splitAt(n: Int): (Repr, Repr) = {
      val l, r = newBuilder
      l.sizeHintBounded(n, this)
      if (n >= 0) r.sizeHint(this, -n)
      var i = 0
      for (x <- this) {
        (if (i < n) l else r) += x
        i += 1
      }
      (l.result, r.result)
    }
    

    It's not unlike your example code of what a Java programmer might come up with.

    I like Scala because, where performance matters, mutability is a reasonable way to go. The collections library is a great example; especially how it hides this mutability behind a functional interface.

    Where performance isn't as important, such as some application code, the higher order functions in Scala's library allow great expressivity and programmer efficiency.


    Out of curiosity, I picked an arbitrary large file in the Scala compiler (scala.tools.nsc.typechecker.Typers.scala) and counted something like 37 for loops, 11 while loops, 6 concatenations (++), and 1 fold (it happens to be a foldRight).

提交回复
热议问题