Lesson contents

Scala — Programming fundamentals

A Scala program can sequence expressions by naming their results with val. The final println sends a human-readable representation to standard output.

A simple example

Follow one calculation

  1. Start with 2 and 3
  2. Do this Add, then print
  3. Result 5
The addition finishes before the program prints its result.
Lesson.scala
object Lesson extends App {
    println(2 + 3)
}
Output
5
Advertisements

Trace an elapsed-time calculation

Use a nonnegative duration in whole minutes as input. Divide it into complete hours and leftover minutes, then print the two results with their units. Int division calculates complete hours and the remainder operator keeps the leftover minutes. String interpolation includes both read-only values in the report.

Trip duration: 134 minutes. Two full hours: 120 minutes. Timetable: 2 h 14 min.
Read a journey time

A travel app records a bus journey as 134 minutes. Divide by 60 to find the full hours, then keep the remaining minutes for a timetable a passenger can read.

Run the example

Use Scala 2.13. Run these commands from the directory containing the example.

scalac Lesson.scala
scala Lesson
Lesson.scala
object Lesson {
  def main(args: Array[String]): Unit = {
    val elapsed = 134
    val hours = elapsed / 60
    val minutes = elapsed % 60
    println(s"$hours h $minutes min")
  }
}
Output
2 h 14 min

For 134 minutes, two full hours account for 120 minutes and leave 14. Multiplying the hours by 60 and adding the remainder reconstructs the input.

Try it yourself

What should the program print at exactly 60 minutes?

Check your answer

It prints 1 h 0 min. An exact multiple of 60 has no leftover minutes.

Scala language specification

Related tags

  • Scala
  • algorithms
  • input and output
  • integer arithmetic