What does map() actually do?

from the CommonsWare Community archives

At April 18, 2019, 7:21pm, Shahood asked:

Hi,

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?


At April 18, 2019, 10:41pm, mmurphy replied:

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

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.


At April 19, 2019, 4:16am, Shahood replied:

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

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

Thanks!