Tag Archives: java 8

Typeclasses in Java 8

Java 8 doesn’t have implicits (for which much thanks will be given in some quarters), which makes it difficult to create typeclasses in a Scala(z)ish fashion. This is one possible compromise.

What’s New In Octarine

Octarine is now at version 0.5, and has been enhanced with New Stuff:

Transformers

Transform records (and anything else you have extractors/lenses for) with a fluent mapping DSL.

BeanRecords

When you have a bean, but want a record, and your key names map (or can be mapped) reflectively onto bean property names:

Reflective JSON serialisation

You lazy so-and-so, you.

Serialisation/deserialisation of maps

Sometimes the “keys” in a JSON array are dynamic values, such as ids, rather than static property names. In that case, you need to be able to serialise/deserialise a map of values rather than a record. The serialisation/deserialisation libraries have been revamped to support this, and a variety of other cases (lists of maps of lists of records, etc.)

Extractors

An Extractor<S, T> may be seen as a partial function from S to T: it can only “extract” a value of type T from a value of type S if such a value (or the material from which one can be created) is present. In Octarine, an Extractor<T, V> is a cross between a Function<T, Optional<V>> and a Predicate<T> . It has three methods:

  • V extract(T source) – extracts a value of type V directly from the source (or fails with an exception).
  • Optional<V> apply(T source) – returns either a value of type V extracted from the source and wrapped in an Optional, or Optional.empty if no such value is available.
  • boolean test(T source) – returns true if the source contains the kind of value that we want, and false otherwise.

The obvious example is a Record , which might or might not contain a value for a given Key<T> . We have:

We can enhance extractors with predicates to look for values matching additional criteria besides existence – for example:

This makes them useful when composing tests on a record:

Which in turn makes them useful when filtering a collection of records:

Any OptionalLens<T, V> in Octarine is also an Extractor<T, V> , and any plain old Lens<T, V> can be turned into an Extractor<T, V> by calling Lens::asOptional on it.

Joink

Joink is a library for joining together collections of Java 8 objects in memory.

Here’s what that looks like:

Currently supported: inner, outer, left-outer and right-outer joins, as well as many-to-one, one-to-many and one-to-one joins (“strict”, which enforces uniqueness, and non-strict which doesn’t).

Soon to come: Octarine integration.

Monoidal FizzBuzz

See the whole thing on github.

Higher-Order FizzBuzz

Clojure (paste into an instarepl to see outputs):

Java 8:

Conclusion: Java 8 is an acceptable functional programming language.