Friday 13 June 2014

Starting up JavaFX in Scala

Scala is great, and JavaFX is a pretty amazing user interface system.  So, I want to combine them.  This is a short note about how to get things going quickly.

A JavaFX start-up class needs to have a main() method just like any other start-up class, and also needs to inherit from Application, so code like this can be written:

class Start extends Application {
    public static void main(String[] args) {
        Application.launch(args);
    }

    public void start(Stage stage) {
        ....
    }
}

The application starts up an instance of the class and passes the main window (the 'Stage') to the start method.

Trying to copy this in Scala results in this:

object Start {
    def main(args: Array[String]) : Unit = {
        Application.launch(args:_*)
    }
}

class Start extends Application {
    override def start(stage: Stage) = {
        ....
    }
}

(args:_* means take the array 'args' and set the elements as individual varargs parameters)

This code won't work.  There are two reasons:  There isn't the connection between the Start object and the Start class in Scala that corresponds to that between static methods and a class in Java.  Secondly, there already is an Application class in the Scala defaults.

We can deal with the first problem by explicitly mentioning the class that the application needs to start up, and the second problem can be fixed by Scala import renaming:

import javafx.application.{Application => FXApplication}

object Start {
    def main(args: Array[String]) : Unit = {
        Application.launch(classOf[Start],args:_*)
    }
}

class Start {
    override def start(stage: Stage) = {
        ....
    }
}

That does it!

In my next programming post I'll show how to get FXML binding working with Scala.


Thursday 12 June 2014

Java 8 - getting rid of the use of nulls

Java 8 will result in a slow revolution in the way Java is programmed.  There are so many new features that have been brought in from functional programming and from other languages.  One of the most powerful in terms of reducing program errors is the Optional class.  This isn't quite Scala's "Optional" but it's still incredibly useful.

Optional is a container for a value and can be considered to be a specialised one-element collection.  The use of generics and type inference in Java 8 means that it can be used pretty much universally as the return value of a method or function that in past Java coding would return either an object or null.

The problem with 'null' is that it's meaningless.  It has no type - it isn't an instance of anything useful: a null value could have come from anywhere.  Optional is typed, so can be used to indicate a typed nothingness!

Here is a method that returns an optional Customer:

public Optional<Customer> findCustomerByName(String name);

Typically in Java to date, it would have been reasonable to return a null value to indicate a search failure.  No longer.  Now code like this can be written:

Optional<Customer> customer = findCustomerByName("Zara");

if(customer.isPresent())
    System.out.println(customer.get()); // get() extracts the value contained in the Optional

This is nice.  The meaning here is explicit, which would not be the case for "customer != null".

But we have only got started.  Using Java 8 lambdas, we can also write this:

customer.ifPresent( cust -> System.out.println(cust));

The value is taken out of the optional and is available within the lambda.

With Java 8 method references, this can be abbreviated further:

customer.ifPresent(System.out::println);

Other methods available with Optional include:

Customer whoToUse = customer.orElse(someoneElse);

use the contained customer if present, otherwise use someoneElse.

Customer cust = customer.orElseThrow(IllegalArgumentException::new);

Throw an exception if the Optional doesn't contain anything.

These are extremely concise compared to what had to be previously written in Java, and the meaning is much clearer.

So, replace setting nulls with Optional.empty() and replace all checking of nulls with the clearer and safer Optional methods - you have nothing to use but NullPointerExceptions!


Sunday 8 June 2014

Essay: The Scales of Eternity

The Scales of Eternity

We are told we live in a universe that is running down, that the time of light and complexity will inevitably end. But that has always been true and perhaps always will be, from the earliest times until the stars are a just brief afterglow of the Big Bang.

At the start, no clocks were possible, but our imaginary clock ticks every 10-44 seconds

This is a time of heat and light, the universe is full of rich activity. Time is strange, before and after intermingled. Then, a clock could tick and time's direction settles. Waves of space and time echo back and forth, particles of all sizes appear, disappear and collide, there is one force binding matter and energy into a unity. Cooling starts, the forces start to separate and then: explosion of space, faster and faster it goes, driven by the separation energy, on and on it goes, the negative gravity stretching space far faster than light, doubling and re-doubling each volume over and over again. After a long, long time, the explosion stops. The last quantum ripples remain, and the energy of the slowing inflation fills everywhere with hot particles. It's cold: not the slightest fraction of the starting heat. Things are slow, the universe is running down. Only a few particles are made now, and they drift slowly across space, occasionally meeting their opposites and annihilating. Space is almost empty.

Clock tick time is from a millionth of a second to a second. There is such heat: this is the time of plasmas, the first of quarks and the force-carrier gluons. The universe is a hot sea of 'colours', strangeness, charm, top, bottom, up, down, the quantum labels of the quarks and their forces. Exponentially, things cool as the universe slowly expands, until the photon types split: light with no mass carries electromagnetic waves without limit. Light with mass has limited time to move and carries the weakest force, felt by neutrinos. Growing and cooling, the first plasma clears as the quarks condense like drops in a mist into protons and neutons, the baryons. Large are the baryons, barely there, a triplet of quarks held by the strong force, which strangely weakens at close range, but look closely at a quark – it may be a string, a vibrating strand. Imagine that strand as a metre in length... how big is a proton? It's a galaxy.

Clock ticks slow from seconds to millennia

Now we see the elements start to form, protons and neutrons pulled together by the residue of the force between quarks. Time passes, years, decades, centuries, hundreds of thousands of years. Electrons condense into orbits around the baryon clusters. The second plasma clears and atoms form. Gases condense, settling into stars, galaxies, clusters of galaxies. For a very brief time the stars burn, explode, condense, burn, explode, condense. On a rock around one star complexity is fueled by the light and life as we know it appears. One species spreads to space. The cycle of the suns is done. The star dwarves give off a red glow for a trillion years, and the galaxies spin like chains of rubies. Then darkness.

Clock ticks slow from a billion years to a trillion years and beyond

The black holes spin. Perhaps civilizations farm black holes for fuel, the twisting space around them providing energy beyond imagining. The sky is filled with quasars, beaming energy across the light-millennia. This could be the true era of life, not the brief flicker of the fusing stars. Trillions of trillions of years.

Even the black holes decay. There is nothing left. Dark and cold re-scaled by powers of powers of ten. There is nothing but the vacuum, everywhere and forever. Except... in orbits tens of billions of light years wide, electrons circle positrons, forming positronium.
Clock ticks become too long to imagine

Positronium atoms dance across the universe, forming - what? At each scale there is furious activity, both chaos and order. As these fade to nearly nothing, a change of perspective takes us back to a reality of action and energy. Will the universe ever really run down to nothing? Perhaps not, when time seems close to eternal at each scale there is always more, and who knows what there might be when the universe is experienced on a scale so long that the time of black holes is to that time what a Planck tick is to ours?


Our universe is falling apart - we are made of the cold ashes of an earlier furnace - but as it falls, there is much that can happen, there are new wonders. We are creatures of fragile complexity in a world that is always on the edge of nothingness.