Code Examples for

Programming in Scala, Third 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. Read lines from a file

  • // 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) 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) 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)) 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 println(oneTwo + " and " + threeFour + " were not mutated.") println("Thus, " + oneTwoThreeFour + " is a new list.")
    List(1, 2) and List(3, 4) were not mutated. Thus, List(1, 2, 3, 4) is a new list.
    // In file next-steps-in-scala/Ex3.scala val twoThree = List(2, 3) val oneTwoThree = 1 :: twoThree println(oneTwoThree)
    List(1, 2, 3)
    // In file next-steps-in-scala/Ex3.scala val oneTwoThree = 1 :: 2 :: 3 :: Nil println(oneTwoThree)

    Step 2. Use tuples


    // In file next-steps-in-scala/Ex3.scala val pair = (99, "Luftballons") println(pair._1) println(pair._2)
    99 Luftballons

    Step 3. Use sets and maps


    // In file next-steps-in-scala/Ex3.scala var jetSet = Set("Boeing", "Airbus") jetSet += "Lear" println(jetSet.contains("Cessna"))
    // 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("Hitch", "Poltergeist") movieSet += "Shrek" println(movieSet)
    // In file next-steps-in-scala/Ex3.scala import scala.collection.immutable.HashSet val hashSet = HashSet("Tomatoes", "Chilies") println(hashSet + "Coriander")
    // In file next-steps-in-scala/Ex3.scala import scala.collection.mutable val treasureMap = mutable.Map[Int, String]() treasureMap += (1 -> "Go to island.") treasureMap += (2 -> "Find big X on ground.") treasureMap += (3 -> "Dig.") println(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" ) println(romanNumeral(4))

    Step 4. Learn to recognize the functional style


    // In file next-steps-in-scala/Ex3.scala def printArgs(args: Array[String]): Unit = { var i = 0 while (i < args.length) { println(args(i)) i += 1 } }
    // In file next-steps-in-scala/Ex3.scala def printArgs(args: Array[String]): Unit = { for (arg <- args) println(arg) }
    // In file next-steps-in-scala/Ex3.scala def printArgs(args: Array[String]): Unit = { args.foreach(println) }
    // In file next-steps-in-scala/Ex3.scala def formatArgs(args: Array[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(Array("zero", "one", "two")) assert(res == "zero\none\ntwo")

    Step 5. Read lines from a file


    // In file next-steps-in-scala/countchars1.scala import scala.io.Source if (args.length > 0) { for (line <- Source.fromFile(args(0)).getLines()) println(line.length + " " + line) } else Console.err.println("Please enter filename")
    $ scala countchars1.scala countchars1.scala
    22 import scala.io.Source 0 22 if (args.length > 0) { 0 51 for (line <- Source.fromFile(args(0)).getLines()) 37 println(line.length + " " + line) 1 } 4 else 46 Console.err.println("Please enter filename")
    22 | import scala.io.Source 0 | 22 | if (args.length > 0) { 0 | 51 | for (line <- Source.fromFile(args(0)).getLines()) 37 | println(line.length + " " + line) 1 | } 4 | else 46 | Console.err.println("Please enter filename")
    // In file next-steps-in-scala/Ex4.scala val lines = Source.fromFile(args(0)).getLines().toList
    // In file next-steps-in-scala/Ex4.scala def widthOfLength(s: String) = s.length.toString.length
    // In file next-steps-in-scala/Ex4.scala var maxWidth = 0 for (line <- lines) maxWidth = maxWidth.max(widthOfLength(line))
    // In file next-steps-in-scala/Ex5.scala val longestLine = lines.reduceLeft( (a, b) => if (a.length > b.length) a else b )
    // In file next-steps-in-scala/Ex5.scala val maxWidth = widthOfLength(longestLine)
    // In file next-steps-in-scala/Ex5.scala for (line <- lines) { val numSpaces = maxWidth - widthOfLength(line) val padding = " " * numSpaces println(padding + line.length + " | " + line) }
    // In file next-steps-in-scala/Ex6.scala import scala.io.Source def widthOfLength(s: String) = s.length.toString.length if (args.length > 0) { val lines = Source.fromFile(args(0)).getLines().toList val longestLine = lines.reduceLeft( (a, b) => if (a.length > b.length) a else b ) val maxWidth = widthOfLength(longestLine) for (line <- lines) { val numSpaces = maxWidth - widthOfLength(line) val padding = " " * numSpaces println(padding + line.length + " | " + line) } } else Console.err.println("Please enter filename")

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

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

    and:

    http://booksites.artima.com/programming_in_scala_3ed

    Copyright © 2007-2016 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.