About the author

My photo

Java, Scala, and everything

Tuesday, July 14, 2009

JavaFX - Defining simple variables.

Ok, so I thought to write JavaFX tutorial. Hope it's going to be useful for somebody. Welcome to part one, about language basics, defining variables and values.

First, you should know what variables/value types are available. There are all the familiar ones (String, Long, Double etc.), but no primitives (long, double etc.). Well, in JavaFX everything is an object. Really. There is also one new type: Duration. It is especially useful in animations, but we'll get to it later.

So there are variables and values. Values are a little like final constants in Java, but only a little. Value of value ( ;) ) can change, but you can't change it explicitly. It can be changed by binding - we'll talk about it in some later part.

So how do you define variables and values? Quite simple:
var a:Float = 5;
Defines variable a of type Float. We can also do something like this:
var a = 5;
Where is variable's type? Well, you don't need to specify it in such case. Type is inferred automatically by JavaFX Script compiler from value assigned to this variable. Isn't it obvious that it is Integer? It could be also Float, yes, and if you want it to be Float, please specify it like in first example.

What about "almost-like-java-constants" values? You define it like that:
def a:Float = 5;
So now there is value defined, and you can't change it. a = 6 will not compile.

Ok, let's look at this new Duration type. Few examples:
var s = 5s;
var m = 2m;
var h = 4h;
s is 5 seconds, m is 2 minutes and h is 4 hours. Quite simple, isn't it? Also arithmetics like adding, multiplying etc works here:
var s = 5s * 4;
var m = 2m + 3m;
var h = (2h + 3m) * 4;
Ok, that's all in this part. In the next one I'll write something about String operations and sequences. Stay tuned!

No comments: