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

前端 未结 6 1063
死守一世寂寞
死守一世寂寞 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条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-05 06:40

    The example is slightly unrealistic, but for complex expressions, it's often far cleaner to use a comprehension:

    def foo = {
      val results = for {
        x <- (1 to 100).view
        y = x + 3 if y > 10
        z <- table get y
      } yield z
      (results take 3).toList
    }
    

    The other advantage here is that you can name intermediate stages of the computation, and make it more self-documenting.

    If brevity is your goal though, this can easily be made into a one-liner (the point-free style helps here):

    def foo = (1 to 100).view.map{3+}.filter{10<}.flatMap{table.get}.take(3).toList
    //or
    def foo = ((1 to 100).view map {3+} filter {10<} flatMap {table.get} take 3).toList
    

    and, as always, optimise your algorithm where possible:

    def foo = ((1 to 100).view map {3+} filter {10<} flatMap {table.get} take 3).toList
    def foo = ((4 to 103).view filter {10<} flatMap {table.get} take 3).toList
    def foo = ((11 to 103).view flatMap {table.get} take 3).toList
    

提交回复
热议问题