Thursday, May 31, 2012

Distance / Time = Speed

I blogged about introducing a Distance datatype using Xtend some time ago, which allows you to write the following:

@Test def distances() {
  assertEquals(, + 2_000.m)
  assertEquals(, ( + 2_000.m) * 2)

We've enhanced this example a bit and put it into the Xtend tutorial project, which you can materialize into your workspace using Eclipse's example wizard.

We added two more datatypes Time and Speed, so that you now can write things like this:

@Test def speed() {
  assertEquals(, (40_000.m + / 60.min)

The datatype Time is defined similarly to the Distance type. It defines operators and some static methods, which when imported as extension method allows you to write things like 60.min etc.
In order to be able to divide some Distance by some Time (i.e. create Speed), you need to define a static operator like so :

@Data class Speed {
  BigDecimal mmPerMsec

  def static operator_divide(Distance d, Time t) {
    new Speed( / t.msec)

Just import this as an extension method and you are able to write :
  (40_000.m + / 60.min

Finally we also want to write Speed literals like

Can you guess how this is done?

(If not, it's in the example :-)
Eclipse updatesite: )