Reputation: 27
If a have a val x = List(2,3,5,8)
and I want to append element 4 to the list, x::a
or a::x
work as expected. But is there an alternative to this notation?
Upvotes: 0
Views: 88
Reputation: 4495
If I understood your question correctly, we have:
val x = List(2,3,5,8)
val a = 4
and you wish to append (in immutable terms) a
to x
.
a::x
works but will return a list with 4
prepended, so not what you asked for. x::a
will not work at all because, well, you can't really prepend a list to an integer.
What you can do, for example, is use the :+
method:
x :+ a // Returns List(2, 3, 5, 8, 4)
Notice however that appending to a List
requires linear time and may therefore be a bad idea, depending on your particular application. Consider using a different data structure if the performance of this operation is important. More information here.
Upvotes: 3