6.1.1 Method for adding two time offsets

We now define a method for +. The method adds two time offsets and returns the sum, which is also a time offset:

// Method on <time-offset>, <time-offset>
define method \+ 	// 1
    (offset1 :: <time-offset>, offset2 :: <time-offset>) 	// 2
 => (sum :: <time-offset>)	// 3
  let sum = offset1.total-seconds + offset2.total-seconds;	// 4
  make(<time-offset>, total-seconds: sum);	// 5
end method \+;	// 6

On line 1, notice that the method is defined on \+, rather than simply on +. When we define a method on + or on another infix function, we need to use a backslash before the function name. The backslash clarifies that we mean the value of the variable + (which is a generic function), and that we are not trying to call the function.

On line 4, we add the values stored in the total-seconds slots of the two instances. On line 5, we make and return a new instance of <time-offset>. We initialize the total-seconds slot to contain the sum calculated in line 4.

To test the method, we need to create two instances of <time-offset>:

define variable *minus-2-hours* =
  make(<time-offset>, total-seconds: - encode-total-seconds (2, 0, 0));
define variable *plus-15-20-45* =
  make(<time-offset>, total-seconds: encode-total-seconds (15, 20, 45)); 

We can add the time offsets:

? *minus-2-hours* + *plus-15-20-45*;
{instance <time-offset>}

The result is a new instance of <time-offset>. We did not save the value returned. (Many environments offer a way to access values returned by the listener.) We can add the time offsets again, and view the total-seconds slot of the result:

? decode-total-seconds(*minus-2-hours* + *plus-15-20-45*);
13
20
45