Scala for the Impatient

OOP1: Classes and Objects

Copyright © Cay S. Horstmann 2015

Declare classes, instance variables, and methods


Appreciate the benefit of immutabilty

Immutable and Mutable Classes

Understand object construction and class parameters


Understand the uniform access principle

The Uniform Access Principle

Use the operator notation for binary methods

More About Methods

Understand objects and the role of companion objects


Companion Objects

Practice declaring classes, instance variables, methods, and operators


Scary looking lab

Part 1: It's About Time

  1. Write a class Time with read-only fields hours and minutes, a method toString, and a method before(other: Time): Boolean that checks whether this time comes before the other. A Time object should be constructed as new Time(h, m), where h is between 0 and 23 and m between 0 and 59. If they aren't, call throw new IllegalArgumentException.
  2. Construct a couple of Time objects and test your before method.
  3. Make it so that a full hour can be constructed as new Time(hrs). There are two different ways. What are they?

Part 2: Uniform Access

  1. In a new worksheet, reimplement the Time class from the preceding exercise so that the internal representation is the number of minutes since midnight (between 0 and 24 × 60 – 1). Do not change the public interface.

    Do not use var or val in the primary constructor!

    class Time(h: Int, m: Int) {
      private val minutesSinceMidnight = ...

    Supply parameterless methods hours, minutes.

  2. Now we'll make this a little harder. In the original class, make minutes into a mutable field, so that the following is okay:
    val start = new Time(13, 0)
    start.minutes = 15
    What did you have to do?
  3. Do the same for the reimplemented class. You need to provide a setter method with the special name property_=, like this:
    def minutes_=(newValue: Int) { ... }
  4. In the original implementation, as changed in part 2b, it would have been possible to corrupt the field values by calling:
    start.minutes = -100
    How can you avoid that in the modified implementation?
  5. Explain what “uniform access” means in this context. What changes does a programmer using the Time class have to make when switching from the original to the reimplemented class?
  6. Why are getters and setters less evil in Scala than in Java?

Part 3: Operators

Do the following with either the original or the reimplemented Time class (your choice):

  1. Change the before method of part 1 so that one can call:
    if (t1 < t2) ...
  2. Add a method - that, given a Time object, yields the number of minutes between them (between -1439 and 1439).
  3. Make it so that a Time object can be constructed without calling new.