Exercise: Adding element at position
We can add an element at a specific position to a mutable list using the add
method. For instance:
Unfortunately, there is no similar function that would allow us to add an element at a specific position to an immutable list. Your task is to define it, and name it plusAt
.
It should be used in the following way:
This function should check if the index is correct. If it is not, it should throw an IllegalArgumentException
. Should consider 0
as a correct index, and add this element to the beginning of the list. Should also consider size
as a correct index, and add this element to the end of the list.
I know at least three significantly different ways to implement this function. One uses a mutable collection, while others use collection processing functions and +
operator. Try to implement it in all three ways.
This problem can either be solved in the below playground or you can clone kotlin-exercises project and solve it locally. In the project, you can find code template for this exercise in functional/collections/PlusAt.kt. You can find there starting code, example usage and unit tests.
Once you are done with the exercise, you can check your solution here.