Importing static members

The Gosu uses statement supports importing static features from a type so you can use them later in your code without verbose syntax. Static features are members of a type that are defined with the static keyword, and so appear on the type itself rather than an instance of the type. The Gosu static imports feature is similar to the Java equivalent, but with more concise syntax that does not require the static keyword during import.

Static features that you can import include:

  • Static properties
  • Static fields
  • Static methods

Gosu static imports are particularly useful to support the Gosu binding expressions feature.

To import static features, at the top of the file, write a uses line that specifies a type, followed by the # character, than the static member name. For the static member name, list the property name, the field name, or a method signature with type names only (omit the argument names). The use of the # character in this case reflects the Gosu feature syntax for a property or method on a type. This syntax is sometimes called feature literal syntax.

To import all static features for a type, use the * character instead of feature literal syntax for a specific member.

The following example imports one method:

uses org.junit.Assert#assertEquals(String, Object, Object)

The following example imports all static features from a class

uses gw.util.money.IMoneyConstants#*   // Imports all static features from IMoneyConstants
Note: Use static imports with caution. Excessive use of unqualified names of static members from outside the scope of a class creates code that is confusing to read.

Example usage of static imports

Create the following example class example.TestClass.

package example

class TestClass {

  // Static field (a field directly on the type, not an instance of it)
  static public var OneHundred : Integer = 100

  // Static method (a method directly on the type, not an instance of it)
  static function helloWorld() {
    print("Hello world")
  }
}

Note that the class contains a static field and a static method. Without using static imports, Gosu code in other classes needs to qualify the field or method:

uses example.TestClass

print(2 + TestClass.OneHundred)

TestClass.helloWorld()

If you import the static members from the type, you can omit the type name before using static members:

// Import all static members from a type (note the #* at the end)
uses example.TestClass#*

// You can now use a static field without specifying what type it is on
print(2 + OneHundred)

// You can call a static function without specifying what type it is on
helloWorld()