2017-01-11

Dart for Java Developers: Into the code

In a previous post, Dart for Java Developers: First Contact I offered you a glimpse at the language by creating a very basic project using the project creation wizard of IntelliJ IDEA. Today I would like to dig a little deeper by showing you how to rewrite a Java program in Dart. I will use a small temperature conversion app which I wrote for a series of talks about Java on mobile devices. You can find the JavaFX version on GitHub.

The program consists of four classes, a user interface definition and a resource bundle. TemperatureConverter is the main class. It loads the ui from an fxml file and instantiates a controller class called FXMLDocumentController. This controller binds ui components and actions to a model class named Model. This class holds the actual domain data and invokes code from the Converter class. It contains a couple of static methods that do the actual temperature calculation. Let us start with this one.

As you can see in the source, although doing different computations, the innards of the methods are mostly the same, that is, doing some arithmetics using the primitive double data type. The method stringToDouble() converts a string to a double value honoring locale specific settings like the decimal mark and the thousands separator. doubleToString() creates a string consisting of a double value with its fractional part omitted if it is zero, and a suffix. How could we do this in Dart?

For your convenience I set up a GitHub repository. Please take a look at converter.dart. Possibly to a bit of a surprise, it does not contain a class, but several top level functions. unitDegreesCelsius, unitDegreesFahrenheit and unitKelvin are compile time constants. _f is declared final, so its value can be assigned only once, but obviously not during compile time. I really like the compact function definition using =>, which takes an expression. If more statements are needed, the traditional body using curly braces comes into play. Also very nice is the string interpolation you can see in _doubleToString(). You can access the value of an expression inside a string by using ${expression}. If the expression is an identifier, the {} can be omitted.

To see the calculations in action I have provided main.dart. If a dart file contains a toplevel main()-function it is called a script. The following screenshot shows the execution of the program in Visual Studio Code.
Editing and running the script in Visual Studio Code

Dart programs and libraries are often distributed as packages. Packages follow certain rules regarding structure and content. You can see a bit of this in the screenshot. I might go into a little more detail in a future post. The json file you can see in the screenshot is not part of that package but helps running the program in Visual Studio Code. Want to try for yourself? Great. Just clone the repo and start playing.

1 comment: