Challenge Two solution at the end of the chapter seems to be wrong.
This is the solution given:
// Challenge 2 - Write a function that removes the first occurrence of a given integer from a list of integers. This is the signature of the function:
// fun removeOne(item: Int, list: List<Int>): List<Int>
fun removeOne(item: Int, list: List<Int>): List<Int> {
val mutableList = list.toMutableList()
mutableList.remove(item)
return mutableList.toList()
}
- This is the documentation for remove:
remove - Kotlin Programming Language
Note for MutableList
this is actually deprecated,
Deprecated: Use removeAt(index) instead.
In Kotlin one should use the MutableList.removeAtfunction instead.
Both for .remove
and .removeAt
, the function does not do what the challenge is asking for. The function removes the item at the provided index.
So if your List is (3, 3, 3, 3, 4, 4, 0, 9) and you call the function to remove 4, according to the challenge question the function should return (3, 3, 3, 3, 4, 0, 9)
But what the provided solution does is remove an item at a certain index, not the provided integer. So the solution given, gives the wrong answer in this case. It will remove the fourth item in the list, not the first occurrence of the integer 4, giving (3, 3, 3, 4, 4, 0, 9)
What the solution should do, is iterate through the list until it finds a match for the provided argument, then remove that item, regardless of the index