scala map example
Sure! Here's an example of using the map
function in Scala:
val numbers = List(1, 2, 3, 4, 5)
val doubledNumbers = numbers.map(_ * 2)
println(doubledNumbers)
In this example, we have a list of numbers [1, 2, 3, 4, 5]
. We use the map
function to apply a transformation to each element of the list. The transformation we apply is multiplying each number by 2.
The result of the map
operation is a new list [2, 4, 6, 8, 10]
, where each element is the original number multiplied by 2.
Finally, we print out the doubledNumbers
list, which will output [2, 4, 6, 8, 10]
.
The map
function is a higher-order function in Scala that takes a function as an argument. It applies this function to each element of the collection and returns a new collection with the results. In this example, the function we passed to map
is a lambda function (_ * 2)
, which multiplies each element by 2.