What is the accepted/recommended syntax for Scala code with lots of method-chaining?

前端 未结 6 1067
死守一世寂寞
死守一世寂寞 2021-02-05 06:29

In Scala I tend to favour writing large chained expressions over many smaller expressions with val assignments. At my company we\'ve sort of evolved a style for th

6条回答
  •  -上瘾入骨i
    2021-02-05 06:53

    I prefer lots of vals:

    def foo = {
      val range = (1 to 100).view
      val mappedRange = range map { _+3 }
      val importantValues = mappedRange filter { _ > 10 } flatMap { table.get }
      (importantValues take 3).toList
    }
    

    Because I don't know what you want to purpose with your code, I chose random names for the vals. There is a big advantage to choose vals instead of the other mentioned solutions:

    It is obvious what your code does. In your example and in the solutions mentioned in most other answers anyone does not know at first sight what it does. There is too much information in one expression. Only in a for-expression, mentioned by @Kevin, it is possible to choose telling names but I don't like them because:

    1. They need more lines of code
    2. They are slower due to pattern match the declared values (I mentioned this here).
    3. Just my opinion, but I think they look ugly

提交回复
热议问题