Wednesday, 31 August 2016

Closing over immutable api with Java8 Streams


WebTarget API, part of JAX-RS 2.0 specification, is implemented in Jersey as a Immutable object , the state of the object doesn't change, after it is created, any operation to mutate will create a new instance of it.

This idiomatic best practice of having immutable objects, whose state I need to change within a declarative style combinators of Java 8 Stream were a bit challenging and is still to me. Lucky for me though, other functional programming libraries for Java came to the rescue.

jOOλ(pronounced Jool) is an excellent functional library which tends to plugs the gaps in Java 8 library towards the Streams API. With that said, the foldLeft operation is what we were looking for, (reduce() could have worked for mutable WebTarget, had additional mechanism to query for the state variables were available, like getting the current list of queryParam)

foldLeft takes an accumulator and a BiFunction between the accumulator and an element from the stream and the accumulator is modified, in our case replaced with an updated copy of WebTarget.