home search about rss feed twitter ko-fi

map Method (Scala 3 Video)

Keys

  • The Scala map method transforms one collection to another collection using the algorithm you supply
  • It’s like a basic for/yield expression (with one generator and no definitions or guards)
  • You supply an algorithm that works on an individual element that’s in the collection. so if it contains Ints, your algorithm works on one Int at a time.
  • It may help to think of “map” as “transform”

Examples:

val xs = List(1, 2, 3)
val ys = xs.map(x => x * 2)
val ys = xs.map(_ * 2)

val ys = xs.map { x =>
    // can be multiple lines
    x * 2
}

map + your algorithm works like this:

    x    y
    ------
    1 => 2
    2 => 4
    3 => 6

Another:

val xs = List("big", "belly", "burger")
val ys = xs.map(x => x.length)
val ys = xs.map(_.length)

map + your algorithm works like this:

    x           y
    -------------
    "big"    => 3
    "belly"  => 5
    "burger" => 6

Ways to think about map

When you type this x, say to yourself, “for EACH x in xs, apply this algorithm to yield a new result”:

val ys = xs.map(x => x * 2)
                ----

map is the same as a basic for expression:

// [1]
val ys = xs.map(x => x * 2)

// [2]
val ys = for x <- xs yield x *2

// [3]
val ys = for
    x <- xs
yield
    x *2

Passing functions into map

def double(i: Int): Int = i * 2
val ys = xs.map(x => double(x))

// shortcuts
val ys = xs.map(double(_))
val ys = xs.map(double)

The function you pass in must match the data type that’s in the collection:

// collection contains Ints, so your algorithm needs to
// accept an Int (needs to be a function that takes an Int):
val nums = List(1, 2, 3)
val doubles = nums.map(_ * 2)
def double(i: Int): Int = i * 2

// collection contains Strings, so your algorithm needs to
// accept an String:
val names = List("Bert", "Ernie")
val nameLengths = names.map(name => name.length)
val nameLengths = names.map(_.length)
def strlen(s: String): Int = s.length

Your algorithm can also return whatever it needs to return:

val nameLengths = names.map(name => (name, name.length))

map method with the Map class

val states = Map(
    "ak" -> "alaska",
    "al" -> "alabama"
)

val newMap = states.map((k,v) => (k.toUpperCase, v.toUpperCase))
val a = Map(
    1 -> 'a',
    2 -> 'b'
)

// return whatever value/type you need:
val b = a.map( (k,v) => (k, v.toUpper) )
val c = a.map( (k,v) => (k.toDouble, v.toUpper) )

// a multiline example
val d = a.map { (k, v) =>
    // can be multiple lines
    (k, v.capitalize)
}

Update: All of my new videos are now on
LearnScala.dev