This article explores different ways to apply a function to each element of a List in Kotlin.

1. Using map() function

The standard approach to apply a given function to the elements of the list is using the map() function. This solution should be used to get a new list, leaving the original list unchanged.

Download Code

Output:

[a, b, c, d]

2. Using replaceAll() function

If you need to in-place transform a list, consider using the replaceAll() function instead of map(). The replaceAll() function can apply a specified function to each element of the list, as shown below:

Download Code

Output:

[a, b, c, d]

3. Using Loop

You can also write our own routine for this simple task. The idea is to iterate over the list using a loop, and transform each encountered element, and insert the element in a new list. This logic would translate to the following code:

Download Code

Output:

[a, b, c, d]

That’s all about applying a function to each element of a List in Kotlin.