YoBre YoBre - 1 year ago 89
Scala Question

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

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
, are obliged to maintain the existing structure.
How can I do?

Thanks to all

Answer Source

If you know that you will be dropping the third element (index 2), then you can simply use

val trunced = internalIdList.take(2) ++ internalIdList.drop(3)

otherwise, if you don't know beforehand what the index will be of the element to remove, you could write a function like the following:

def removeIndex(ix: Int) = if (internalIdList.size < ix) internalIdList
                           else internalIdList.take(ix) ++ internalIdList.drop(ix+1)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download