As you may know, the OpenJFX Compiler project has been making improvements to the JavaFX language out in the open, so I'd like to get you up to speed on these in preparation for when the entire JavaFX SDK 1.0 is released yet this fall. Today I'll discuss some of these language changes:
def Jam
A keyword has been introduced, named def, that is designed to be used to define constants in JavaFX. The value of a variable declared with def may not be subsequently changed, except through the bind mechanism. For example, in the code snippet below, the second line won't compile because it is attempting to assign a value to PI after it has been declared with def:
def PI:Number = 3.14159;
PI = 22.0 / 7.0; // This line doesn't compile
Use var Everywhere -- attribute is History
For consistency, the var keyword is now used to declare instance variables, replacing the attribute keyword. The result is that var is used to declare local variables, instance variables, and module (script) level variables. Of course, we've been using var all along to declare local variables in a function. The following (contrived) JavaFX program contains examples of using var and def in the ways just discussed:
/*
* DeclaringVariablesMain.fx -
* An example of declaring variables in JavaFX SDK 1.0
*
* Developed 2008 by James L. Weaver (jim.weaver at jmentor.com)
* to demonstrate how to declare variables in using def and var in JavaFX
*/
//script-level variable that also is a constant (def)
def PI:Number = 3.14159;
class Vehicle {
//instance variables
var wheels:Integer;
var wheelDiameter:Number;
function getVehicleType():String {
//local variable
var types:String[] = [
"Unicycle",
"Motorcycle",
"Tricycle",
"Car"
];
types[wheels - 1];
}
function totalWheelsCircumference():Number {
wheels * wheelDiameter * PI;
}
}
//script-level variable
var myG6 =
Vehicle {
wheels: 4
wheelDiameter: 14
}
//println is a built-in function now
println("Total wheels circumference of my G6 {myG6.getVehicleType()} "
"is:{myG6.totalWheelsCircumference()}");
Here is the output that I received when running this program:
Total wheels circumference of my G6 Car is:175.92904
Other Noteworthy Items
As shown above, we no longer have to import java.lang.System to use the print and println functions. Also, remember that since JavaFX is a block expression language, return statements aren't necessary in the functions above. The value of a block is the last expression in the block.
In future posts I'll continue discussing JavaFX languages enhancements that have been introduced in the OpenJFX Compiler project. This will help you prepare for the JavaFX SDK 1.0 release that is just around the corner!
Regards,
Jim Weaver
http://JavaFXpert.com
Recent Comments