Code Examples for

Programming in Scala, Fifth Edition

Return to chapter index

3 Next Steps in Scala

  • Step 1. Use lists
  • Step 2. Use tuples
  • Step 3. Use sets and maps
  • Step 4. Learn to recognize the functional style
  • Step 5. Transform with map and for-yield

  • // In file next-steps-in-scala/Ex1.scala val big = new java.math.BigInteger("12345")
    // In file next-steps-in-scala/Ex1.scala val greetStrings = new Array[String](3) greetStrings(0) = "Hello" greetStrings(1) = ", " greetStrings(2) = "world!\n" for i <- 0 to 2 do print(greetStrings(i))
    // In file next-steps-in-scala/Ex2.scala val greetStrings: Array[String] = new Array[String](3)
    // In file next-steps-in-scala/Ex2.scala greetStrings(0) = "Hello" greetStrings(1) = ", " greetStrings(2) = "world!\n"
    // In file next-steps-in-scala/Ex2.scala for i <- 0 to 2 do print(greetStrings(i))
    greetStrings(0) = "Hello"
    greetStrings.update(0, "Hello")
    // In file next-steps-in-scala/Ex3.scala val greetStrings = new Array[String](3) greetStrings.update(0, "Hello") greetStrings.update(1, ", ") greetStrings.update(2, "world!\n") for i <- 0.to(2) do print(greetStrings.apply(i))
    // In file next-steps-in-scala/Ex3.scala val numNames = Array("zero", "one", "two")
    // In file next-steps-in-scala/Ex3.scala val numNames2 = Array.apply("zero", "one", "two")

    Step 1. Use lists


    // In file next-steps-in-scala/Ex3.scala val oneTwoThree = List(1, 2, 3)
    // In file next-steps-in-scala/Ex3.scala val oneTwo = List(1, 2) val threeFour = List(3, 4) val oneTwoThreeFour = oneTwo ::: threeFour
    // In file next-steps-in-scala/Ex3.scala val twoThree = List(2, 3) val oneTwoThree = 1 :: twoThree
    // In file next-steps-in-scala/Ex3.scala val oneTwoThree = 1 :: 2 :: 3 :: Nil

    Step 2. Use tuples


    // In file next-steps-in-scala/Ex3.scala val pair = (99, "Luftballons") val num = pair(0) // type Int, value 99 val what = pair(1) // type String, value "Luftballons"

    Step 3. Use sets and maps


    // In file next-steps-in-scala/Ex3.scala var jetSet = Set("Boeing", "Airbus") jetSet += "Lear" val query = jetSet.contains("Cessna") // false
    // In file next-steps-in-scala/Ex3.scala jetSet = jetSet + "Lear"
    // In file next-steps-in-scala/Ex3.scala import scala.collection.mutable val movieSet = mutable.Set("Spotlight", "Moonlight") movieSet += "Parasite" // movieSet now contains: "Spotlight", "Moonlight", "Parasite"
    // In file next-steps-in-scala/Ex3.scala import scala.collection.immutable.HashSet val hashSet = HashSet("Tomatoes", "Chilies") val ingredients = hashSet + "Coriander" // ingredients contains "Tomatoes", "Chilies", "Coriander"
    // In file next-steps-in-scala/Ex3.scala import scala.collection.mutable val treasureMap = mutable.Map.empty[Int, String] treasureMap += (1 -> "Go to island.") treasureMap += (2 -> "Find big X on ground.") treasureMap += (3 -> "Dig.") val step2 = treasureMap(2) // "Find big X on ground."
    // In file next-steps-in-scala/Ex3.scala val romanNumeral = Map( 1 -> "I", 2 -> "II", 3 -> "III", 4 -> "IV", 5 -> "V" ) val four = romanNumeral(4) // "IV"

    Step 4. Learn to recognize the functional style


    // In file next-steps-in-scala/Ex3.scala def printArgs(args: List[String]): Unit = var i = 0 while i < args.length do println(args(i)) i += 1
    // In file next-steps-in-scala/Ex3.scala def printArgs(args: List[String]): Unit = for arg <- args do println(arg)
    // In file next-steps-in-scala/Ex3.scala def printArgs(args: List[String]): Unit = args.foreach(println)
    // In file next-steps-in-scala/Ex3.scala def formatArgs(args: List[String]) = args.mkString("\n")
    // In file next-steps-in-scala/Ex3.scala println(formatArgs(args))
    // In file next-steps-in-scala/Ex3.scala val res = formatArgs(List("zero", "one", "two")) assert(res == "zero\none\ntwo")

    Step 5. Transform with map and for-yield


    val adjectives = List("One", "Two", "Red", "Blue")
    val nouns = adjectives.map(adj => adj + " Fish") // List(One Fish, Two Fish, Red Fish, Blue Fish)
    val nouns = for adj <- adjectives yield adj + " Fish" // List(One Fish, Two Fish, Red Fish, Blue Fish)
    val lengths = nouns.map(noun => noun.length) // List(8, 8, 8, 9)
    val lengths = for noun <- nouns yield noun.length // List(8, 8, 8, 9)
    val ques = Vector("Who", "What", "When", "Where", "Why") val usingMap = ques.map(q => q.toLowerCase + "?") // Vector(who?, what?, when?, where?, why?) val usingForYield = for q <- ques yield q.toLowerCase + "?" // Vector(who?, what?, when?, where?, why?)
    val startsW = ques.find(q => q.startsWith("W")) // Some(Who) val hasLen4 = ques.find(q => q.length == 4) // Some(What) val hasLen5 = ques.find(q => q.length == 5) // Some(Where) val startsH = ques.find(q => q.startsWith("H")) // None
    startsW.map(word => word.toUpperCase) // Some(WHO)
    for word <- startsW yield word.toUpperCase // Some(WHO)
    startsH.map(word => word.toUpperCase) // None
    for word <- startsH yield word.toUpperCase // None

    For more information about Programming in Scala, Fifth Edition (the "Stairway Book"), please visit:

    http://www.artima.com/shop/programming_in_scala_5ed

    and:

    http://booksites.artima.com/programming_in_scala_5ed

    Copyright © 2007-2020 Artima, Inc. All rights reserved.

    Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.