Coding cross-platform using imports

We've already seen the import keyword that allows us to import all the classes of a module. This keyword can be used to write some cross-platform code. Indeed, it is the preferred way to do so, when working with packages that have the same layout. It has the advantage of being easily readable and does not mean adding three lines every time you want to access a platform-specific package.

So, here's a simple example: imagine you want to target Neko and PHP and want to use the println method available in neko.Lib.println and php.Lib.println (these methods allow you to write a line of text on the stdout). As you can see here, regarding what we are going to use, the neko and php package have the same layout (indeed, they have the same layout for quite a lot of their classes). So, we can write the following code:

#if php import php.Lib; #elseif neko import neko.Lib; #end class Main
{
public static function main()
{
Lib.println("Hello World");
}
}

In this example, we can use the php.Lib or neko.Lib class by simply using its name (Lib), as the good one is imported depending on the current compilation target. If we didn't do that, the code would have looked like the following:

class Main
{
public static function main() {
#if php php.Lib.println("Hello World");
#elseif neko
neko.Lib.println("Hello World");
#endif
}
}

As you can see, this is pretty difficult to read although here we have almost no logic and only one instruction.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.85.221