How to remove an item from a list in Scala having only its index?

YoBre picture YoBre · Sep 17, 2013 · Viewed 28.2k times · Source

I have a list as follows:

val internalIdList: List[Int] = List()

internalIdList = List(11, 12, 13, 14, 15)

From this list would remove the third element in order to obtain:

internalIdList = List(11, 12, 14, 15)

I can not use a ListBuffer, are obliged to maintain the existing structure. How can I do?

Thanks to all

Answer

Rok Kralj picture Rok Kralj · Jul 21, 2014

There is a .patch method on Seq, so in order to remove the third element you could simply do this:

List(11, 12, 13, 14, 15).patch(2, Nil, 1)

Which says: Starting at index 2, please remove 1 element, and replace it with Nil.

Knowing this method in depth enables you to do so much more than that. You can swap out any sublist of a list with arbitrary other.