Title: For Looping
Slug: for_looping
Summary: For Loops Using Scala.
Date: 2017-01-03 12:00
Category: Scala
Tags: Basics
Authors: Chris Albon
This tutorial was inspired by the awesome Scala Cookbook.
In [8]:
val staffMembers = Array("Jason Miller", "Steve Miller", "Sally Fields")
In [9]:
// Create a value that is the output, then for each person in staff
val staffFirstNames = for (person <- staffMembers) yield {
// Upper case the name
val upperCaseFullNames = person.toUpperCase
// Get the first name by splitting the full name by space and taking the first element
val firstName = upperCaseFullNames.split(" ")(0)
// Return the first name
firstName
}
In [10]:
// View the returned values
staffFirstNames
Out[10]:
In [11]:
// Create a value that is the output, then for each person in staff with the last name of Miller
val staffWithLastNameMiller = for (person <- staffMembers if person.split(" ")(1) == "Miller") yield {
// Get the first name by splitting the full name by space and taking the first element
val firstName = person.split(" ")(0)
// Return the first name
firstName
}
In [12]:
// View the returned values
staffWithLastNameMiller
Out[12]:
In [13]:
// Create a value that is the output, then for each person and index, yield
val staffNamesAndIndex = for ((person, i) <- staffMembers.zipWithIndex) yield {
// Upper case the name
val firstName = person.split(" ")(0)
// Return a tuple with the first name and index
(firstName, i)
}
In [14]:
// View the returned values
staffNamesAndIndex
Out[14]: