Optional Arguments in Methods

Method definitions may also specify optional arguments. Optional arguments are arguments that are given default values, and therefore do not need to be provided when calling the method. The use of optional arguments can greatly simplify writing code in steve.

To make an argument optional, you need to provide it with a default value. To do so, you'll need to modify the argument definition to include the text = value after the argument name. For example, a variable called theHeight with keyword with-height could be given a default value like this: with-height theHeight = 100 (int). Default values for optional arguments must be literal values (and not expressions or variables).

Below is an example of a method defined with a set of optional arguments.

        # Create a new agent, with some default values.

        + to create-new-agent with-color color = (1, 0, 0) (vector) 
                with-energy energy = 100 (int)
                with-radius radius = 10 (int) 
                with-name name = "agent" (string):

The method above could be called in a number of ways, optionally including or excluding each of the arguments:

        # no arguments 
        self create-new-agent.

        # some of the arguments 
        self create-new-agent with-energy 10 with-name "Becky".

        # all of the arguments
        self create-new-agent with-color (1, 1, 1) 
                with-energy 100
                with-radius 20
                with-name "Robert".