As a quick note today, in this post I’ll share some examples of the Scala map
method as it works on sequences like the List
, Vector
, and Seq
classes.
map == transform
Basically you can think of map
as meaning transform: it lets you transform one collection into another. For instance, these examples in the Scala REPL show how to transform a list of strings into a list of integers, where the integers correspond to the length of each string:
scala> val names = List("Kim", "Julia", "Adam") val names: List[String] = List(Kim, Julia, Adam) scala> val nameLengths = names.map(name => name.length) val nameLengths: List[Int] = List(3, 5, 4) scala> val nameLengths = names.map(_.length) val nameLengths: List[Int] = List(3, 5, 4)
As those examples show, the map method transforms the first list — List("Kim", "Julia", "Adam")
— into the second list — List(3, 5, 4)
.
Another map method example
Here’s another example that transforms the lowercase names in the first list into the capitalized names in the second list:
scala> val lcNames = Vector("kim", "julia", "adam") val lcNames: Vector[String] = Vector(kim, julia, adam) scala> val ucNames = lcNames.map(_.capitalize) val ucNames: Vector[String] = Vector(Kim, Julia, Adam)
Finally, here’s another example that shows how to multiply each number in one list to create another:
scala> val xs = Seq(1, 2, 3) val xs: Seq[Int] = List(1, 2, 3) scala> val ys = xs.map(_ * 2) val ys: Seq[Int] = List(2, 4, 6)
The Scala map method is equivalent to a simple for/yield expression
If it helps, you can think of the Scala map
method as being a replacement for for
/yield
loops. For instance, that last example is equivalent to this much longer expression in Scala 3:
val xs = Seq(1, 2, 3) val ys = for x <- xs yield x * 2
this post is sponsored by my books: | |||
#1 New Release |
FP Best Seller |
Learn Scala 3 |
Learn FP Fast |
Summary
In summary, if you wanted to see how to use the Scala map
method, I hope these examples that use sequences like List
, Vector
, and Seq
are helpful.