3.1.2 Two methods with the same name

For fun, we can change say-greeting to take a different action for integers, such as to print a message:

Your lucky number is 7.

To make this change, we define another method, also called say-greeting. This method has one required parameter named greeting, which has the type constraint <integer>.

define method say-greeting (greeting :: <integer>)
  format-out("Your lucky number is %s.\n", greeting);
end;
? say-greeting(*my-number*);
Your lucky number is 7.

A Dylan method is similar to a procedure or subroutine in other languages, but there is an important difference. You can define more than one method with the same name. Each one is a method for the same generic function. Figure 3.1 shows how you can picture a generic function.

When a generic function is called, it chooses the most appropriate method to call for the arguments. For example, when we call the say-greeting generic function with an integer, the method whose parameter is of the type <integer> is called:

? say-greeting(1000);
Your lucky number is 1000.

When we call the say-greeting generic function with an argument that is not an integer, the method whose parameter is of the type <object> is called:

? say-greeting("Buenos Dias");
Buenos Dias
Figure 3.1 The say-greeting generic function and its methods.
Generic function say-greeting
define method say-greeting (greeting :: <object>)
  format-out("%s\n", greeting);
end;
define method say-greeting (greeting :: <integer>)
  format-out("Your lucky number is %s.\n", greeting);
end;