Exercise: Implement map
In this chapter, you've seen already how map
can be implemented, but this time it will be your task to implement it yourself. So make your own implementation, without looking at what was presented in this chapter. As a help, you can take a look at implementations of filter
and flatMap
. Here you have a couple of examples how map
can be used:
This function should be an extension function on Iterable
, that returns List
. Consider what is the size of the result collection. If the actual receiver type is Collection
, you can take its size
, otherwise you can use 10
as the initial size for the result list.
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/Map.kt. You can find there example usage and unit tests.
You can also find there simplified implementations of onEach
, filter
and flatMap
. Use them as inspiration. You can also notice, that to prevent you from using map
from the Kotlin standard library, I used a feature called import alias, so I imported this function under a different name.
Once you are done with the exercise, you can check your solution here.