Saturday, August 6, 2011

First Steps with Fantom

I'm now finally getting around to taking my first steps with Fantom, even though I thought I would months ago. Where else would I start then "Hello World", and while I'm here, I'll toss in a comparison to the Java and Groovy versions for good measure:

Below is your classic Java "Hello World" program:

    public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}

Here is a Fantom version of the same program.

    class HelloWorld {
static Void main(Str[] args) {
echo("Hello World!")
}
}

There are a few differences worth noting:

  • The public keyword is not required.
  • The void keyword maps to a Void type.
  • The equivalent to String in Java is Str in Fantom.
  • The semicolon ending the singular statement in the Java version is not present in the Fantom version, in fact, including it would cause an error.

Also, the argument to the main method in the Java version is not required in the Fantom version:

 class HelloWorld { static Void main() { echo("Hello World!") } } 

Since I spend most of time with Groovy, I thought I'd consider the Groovy version. Like the Fantom version, the public keyword is not required, but the declared argument to the main method is, although we don't have to declare a type:

    class HelloWorld {
static void main(args) {
println "Hello World"
}
}

Additionally, the parentheses are optional and unlike with the Fantom version, an ending semicolon is allowed.

Now back to Fantom and getting the greeting printed out on the screen. The Fantom class can be placed in a file and run using the fan command:

  $ fan HelloWorld.fan
Hello World!

With Groovy, the println call can simply be placed in a file and executed as a script using the groovy command:

  $ cat hello.groovy
println "Hello World!"

$ groovy hello.groovy
Hello World!

Knowing this, I thought I'd try doing something similar in Fantom:

  $ cat hello.fan
echo("Hello World!")

$ fan echo.fan
/home/prystasj/workspace/Fantom/echo.fan(2,1): Expected 'class', not 'echo'
ERROR: cannot compile script

Unfortunately, we don't get the same results, but Fantom does have an interactive shell we can use, fansh:

  $ fansh
Fantom Shell v1.0.59 ('?' for help)
fansh> echo("Hello World!")
Hello World!
fansh> exit

Next, let's have the Fantom class make use of the array representing the arguments passed into the main method. In Fantom, arrays are also zero-based and accessed in the same way we are all used to:

   class HelloWorld {
static Void main(Str[] args) {
echo("Hello and " + args[0])
}
}

Running the progam with a single argument will have the argument included in the output:

  $ fan HelloWorld.fan goodbye
Hello and goodbye

No comments:

Post a Comment