Functions

Declare a function by using the function keyword. Gosu uses the term method for a function that is part of another type. In Gosu, types follow the variable or function definition, separated by a colon. In contrast, Java types precede the variable or parameter name with no delimiter. To return a value, add a statement with the return keyword followed by the value. The following simple function returns a value:

public function createReport(user : User) : Boolean {
  return ReportUtils.newReport(user, true)
}

Method invocation in Gosu looks familiar to programmers of imperative languages, particularly Java. Just use the period symbol followed by the method name and the argument list in parentheses:

obj.createReport(myUser)

Pass multiple parameters, which can be Gosu expressions, delimited by commas, just as in Java:

obj.calculate(1, t.Height + t.Width + t.Depth)

In some cases, such as in-line functions in Gosu programs, functions are not attached to a class or other type. You call such functions directly in your code. A rare globally available function for any Gosu code is print. Call that function with a String argument to write data to the system console or other default output stream. For example, the following line prints text to the console:

print("Hello Gosu!")

Gosu supports access control modifiers (public, private, internal, and protected). These modifiers have the same meaning as in Java. For example, if you mark a method public, any other code can call that method.

Gosu also supports static methods, which are methods on the type rather than on object instances.

If the return type for a method is not void, all possible code paths in the method must contain a return statement and return a value. The set of all paths includes all outcomes of conditional execution, such as if and switch statements. This requirement is identical to the analogous requirement in Java. The Gosu editor notifies you at compile time if your code violates this requirement.

See also