Preferred way to create a Scala list

后端 未结 10 2670
走了就别回头了
走了就别回头了 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:29

    You want to focus on immutability in Scala generally by eliminating any vars. Readability is still important for your fellow man so:

    Try:

    scala> val list = for(i <- 1 to 10) yield i
    list: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
    

    You probably don't even need to convert to a list in most cases :)

    The indexed seq will have everything you need:

    That is, you can now work on that IndexedSeq:

    scala> list.foldLeft(0)(_+_)
    res0: Int = 55
    

提交回复
热议问题