Practice

Scala exercises

Make a change, predict what it will do, and compare the result.

  1. 1

    Scala Basics

    Run a small program with an entry point.

    Adapt the lesson example. Change one value or element, predict the result, and explain why it changes.

    Show starting example
    Scala
    object Main {
      def main(args: Array[String]): Unit = {
        val name = "Ada"
        println(s"Hello, $name")
      }
    }
  2. 2

    Scala Functions as Values

    Define a method and pass it to a higher-order function.

    Predict twice(square, 2).

    Reveal answer and reasoning

    square(2) is 4 and square(4) is 16.

    Show starting example
    Scala
    object Main {
      def square(n: Int): Int = n * n
    
      def main(args: Array[String]): Unit = {
        val twice = (f: Int => Int, x: Int) => f(f(x))
        println(square(5))
        println(twice(square, 3))
      }
    }
  3. 3

    Scala Case Classes and Pattern Matching

    Define a data class and take it apart with match.

    Add a case for points on the y-axis.

    Reveal answer and reasoning

    Add case Point(0, y) => s"on y-axis at $y" before the catch-all.

    Show starting example
    Scala
    object Main {
      case class Point(x: Int, y: Int)
    
      def describe(p: Point): String = p match {
        case Point(0, 0) => "origin"
        case Point(x, 0) => s"on x-axis at $x"
        case _ => "elsewhere"
      }
    
      def main(args: Array[String]): Unit = {
        println(describe(Point(0, 0)))
        println(describe(Point(4, 0)))
        println(describe(Point(1, 2)))
      }
    }
  4. 4

    Scala Collections: map and filter

    Transform and filter an immutable List without loops.

    Predict scores.filter(s => s > 80).

    Reveal answer and reasoning

    It keeps 82 and 91, giving List(82, 91).

    Show starting example
    Scala
    object Main {
      def main(args: Array[String]): Unit = {
        val scores = List(82, 91, 76)
        val curved = scores.map(s => s + 5)
        println(curved)
        println(curved.filter(s => s >= 90).sum)
      }
    }
  5. 5

    Scala Maps and Option

    Look up a key without nulls by using Option.

    Predict ages.get("Grace").map(a => a + 1).

    Reveal answer and reasoning

    Some(46); map applies the function only when a value is present.

    Show starting example
    Scala
    object Main {
      def main(args: Array[String]): Unit = {
        val ages = Map("Ada" -> 36, "Grace" -> 45)
        println(ages.get("Ada"))
        println(ages.get("Linus"))
        println(ages.getOrElse("Linus", 0))
      }
    }