AS3 Package level functions and Java static imports

It’s a hidden treasure for lot of people but AS3 provides a mechanism to declare functions like setTimeout or setInterval called package level functions. These functions are defined inside packages like flash.utils.setInterval or flash.utils.setTimeout but can be used as if they were static functions.

This is a feature widely used in FlexUnit but that can be used in lots of other circumstances to reduce the amount of code and reduce its verbosity.

The mechanism to create a package level function is pretty simple. Here are the steps required to create a custom package function:

  • You create a class where the function will be defined. i.e: your/package/Assert.as
  • You declare a public function at the package level. Note that there’s no class definition.
    package my.pack
    {
        public function assert()
        {
        }
    }
  • Then you can use it from every where you wish
  • package
    {
        import my.pack.assert;
       
        public class testPackagefunctions
        {
            public function testPackagefunctions()
            {
                assert();
            }
        }
    }

When creating package level functions, the only restriction to bear in mind, is that the function name exposed must be the same name as the name of the file that contains it. i.e. If I expose the assert function, the filename that defines it must be assert.as. This implies that there can only be one function definition per file. If you need more you can create as many files as you need.

Package level functions in AS3 are directly comparable to static imports in Java. In java we can write code like:

package {
    import static my.pack.Assert.*;

    public static void main(String[] args) {
        assert();
    }
}

By using an static import in Java, static methods defined in the Assert class (in the example above) are made available directly so there’s no need to write Assert.assert. Again this is a feature used a lot in jUnit, Hamcrest or lamdaj libraries.

Autocompletion in Java in regards to static imports is not automatic. If you want to have autocompletion with static imports you can use Preferences > Java > Editor > Favorites and add there the Types or classes you want to use static imports for.

Show Comments

Hide Comments

Comments are closed.