Preferred way to create a Scala list
ListBuffer
is a mutable list which has constant-time append, and constant-time conversion into a List
.
List
is immutable and has constant-time prepend and linear-time append.
How you construct your list depends on the algorithm you'll use the list for and the order in which you get the elements to create it.
For instance, if you get the elements in the opposite order of when they are going to be used, then you can just use a List
and do prepends. Whether you'll do so with a tail-recursive function, foldLeft
, or something else is not really relevant.
If you get the elements in the same order you use them, then a ListBuffer
is most likely a preferable choice, if performance is critical.
But, if you are not on a critical path and the input is low enough, you can always reverse
the list later, or just foldRight
, or reverse
the input, which is linear-time.
What you DON'T do is use a List
and append to it. This will give you much worse performance than just prepending and reversing at the end.
And for simple cases:
val list = List(1,2,3)
:)