What does map() actually do?



I’m having difficulty understanding what map() actually does. Whatever we achieved using map() in examples on pg 52 of Elements of Kotlin 0.1, that could have been achieved in the following way too:

  1. val things = listOf("foo", "bar", "goo")
     things.forEach { println(it.toUpperCase()) }
  2. val primes = listOf(1, 2, 3, 5, 7)
     primes.forEach { println( 1.0 / it ) }

So, what was the real purpose of map() in these examples?


It converts a collection of one sort of object to a collection of another sort of object. That includes:

  • Converting data types (e.g., using map() to convert a List<ThingYouGotFromYourWebService> to a List<ThingYouWantToUseInYourApp>

  • Converting data within the same type (e.g., using map() to convert a List<String> of mixed-case strings to a List<String> of all-caps strings)

The purpose was to use map().

The problem with a programming language book is that not everything can be covered first. Books are linear. Some things are covered before other things. I elected to cover branches and loops before classes, and I needed collections to cover loops. Perhaps that was not the best choice, and I might reconsider it.


Got it now. To understand better, I did the following:

val primes = listOf(1, 2, 3, 5, 7)
val primesDouble : MutableList<Double> = ArrayList()
        .map { 1.0 / it }
        .forEach { primesDouble.add(it) }
primesDouble.forEach { println(it) }