Preferred way to create a Scala list

后端 未结 10 2694
走了就别回头了
走了就别回头了 2020-12-02 04:31

There are several ways to construct an immutable list in Scala (see contrived example code below). You can use a mutable ListBuffer, create a var list and modif

10条回答
  •  长情又很酷
    2020-12-02 05:26

    I always prefer List and I use "fold/reduce" before "for comprehension". However, "for comprehension" is preferred if nested "folds" are required. Recursion is the last resort if I can not accomplish the task using "fold/reduce/for".

    so for your example, I will do:

    ((0 to 3) :\ List[Int]())(_ :: _)
    

    before I do:

    (for (x <- 0 to 3) yield x).toList
    

    Note: I use "foldRight(:\)" instead of "foldLeft(/:)" here because of the order of "_"s. For a version that does not throw StackOverflowException, use "foldLeft" instead.

提交回复
热议问题