I'm trying to test whether a double provided through a listener monotonically increases with each call.
For this, I'm keeping another double for comparison and update that at the end of the listener lambda:
double lastProgress = 0;
operator.addProgressListener(progress -> {
assertThat(progress, greaterThanOrEqualTo(lastProgress));
lastProgress = progress;
});
However, this naturally results in a compilation error (Local variable lastProgress defined in an enclosing scope must be final or effectively final), since lastProgress is being altered.
For long variables, a workaround would be to use a final instance of AtomicLong, and set its value accordingly. For doubles, their value could be mapped to long as described here, resulting in the following code:
AtomicLong lastProgress = new AtomicLong(Double.doubleToLongBits(0));
operator.addProgressListener(progress -> {
assertThat(progress, greaterThanOrEqualTo(Double.longBitsToDouble(lastProgress.get())));
lastProgress.set(Double.doubleToLongBits(progress));
});
Even though this works, it's quite inconvenient and not trivial to understand what's going on.
As Java comes with no built-in class like AtomicDouble, is there a convenient way of obtaining a mutuable, final object representing a double?