If you run the example, you should be presented with the values 1, 3, 6, 10, 15,
21, 28, 36, and 45.
Returning from a Function
The return keyword allows a function to end anywhere in its body code. For example, if you wanted to
exit a function early, you could place the return keyword where you wanted the function to exit, and
the rest of the function code would be skipped:
public static function someFunction()
{
// do code
if ( i < 20 )
return;
// more code
}
Here, the pretend function someFunction would exit if the variable i is less than the value 20.
Chapter 4: Controlling the Flow of Information
87
Using the return keyword, you could also have the function return a value by supplying the value to
return after the return keyword:
public static function someFunction() : Int
{
// do code
if ( i < 20 )
return i;
// more code
}
Here, the value of i is returned from the function when the function is exited.
Functions that do not return a value are said to return Void .
Function Type Inference
The types assigned to each parameter of a function do not need to be specified but can be set by the
compiler using type inference.
Pages:
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205