Preferred way to create a Scala list

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

    Using List.tabulate, like this,

    List.tabulate(3)( x => 2*x )
    res: List(0, 2, 4)
    
    List.tabulate(3)( _ => Math.random )
    res: List(0.935455779102479, 0.6004888906328091, 0.3425278797788426)
    
    List.tabulate(3)( _ => (Math.random*10).toInt )
    res: List(8, 0, 7)
    

提交回复
热议问题