Title: Mapping A Function To A Collection
Slug: mapping_a_function_to_a_collection
Summary: Mapping A Function To A Collection Using Scala.
Date: 2017-01-03 12:00
Category: Scala
Tags: Basics
Authors: Chris Albon

If you want to learn more, check out Scala Cookbook and Programming in Scala.

Preliminaries


In [3]:
import scala.collection.mutable.ArrayBuffer

Create Collection


In [6]:
// Create an array of strings
var birds = ArrayBuffer("Hawk", "Condor", "Eagle", "Pigeon")

Create Function


In [12]:
// Create a function that returns the length of a string
val getLength = (i: String) => i.length

Map The Function To The Collection


In [15]:
// Map the function to the array
birds.map(getLength)


Out[15]:
ArrayBuffer(4, 6, 5, 6)

Map An Anonymous Function To The Collection


In [18]:
// Map the anonymous function to the collection
birds.map(_.toUpperCase)


Out[18]:
ArrayBuffer(HAWK, CONDOR, EAGLE, PIGEON)