Mapping A Function To A Collection

Preliminaries

import scala.collection.mutable.ArrayBuffer

Create Collection

// Create an array of strings
var birds = ArrayBuffer("Hawk", "Condor", "Eagle", "Pigeon")

Create Function

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

Map The Function To The Collection

// Map the function to the array
birds.map(getLength)
ArrayBuffer(4, 6, 5, 6)


Map An Anonymous Function To The Collection

// Map the anonymous function to the collection
birds.map(_.toUpperCase)
ArrayBuffer(HAWK, CONDOR, EAGLE, PIGEON)