This article explores different ways to swap two elements of a list in Kotlin.

1. Using Collections.swap() function

The Collections.swap() function swaps the elements at the specified positions in the specified list. It can be used as follows:

Download Code

Output:

[1, 4, 3, 2, 5]

 
If your input is an array, you can use the Collections.swap() function to swap two elements in it. Since the Collections.swap() function accepts a list, you can get a fixed-size list “backed” by the array. Now any changes made to the backed list are reflected in the array as well.

Download Code

Output:

[1, 4, 3, 2, 5]

2. Using Custom Logic

You can write your utility function for swapping two elements in a list. This can be implemented as follows:

Download Code

Output:

[1, 4, 3, 2, 5]

 
Here’s an equivalent way to do it for arrays:

Download Code

Output:

[1, 4, 3, 2, 5]

That’s all about swapping two elements of a list in Kotlin.