Adding Your Own Type

A witness, a helper and an instance, the laws they must keep, and a Path at the end.

"Nor did I deem that thou, a mortal man, / Could'st by a breath annul and override / The immutable unwritten laws of Heaven."

— Sophocles, Antigone (trans. F. Storr)

No compiler reads the functor and monad laws, yet every caller of your instance relies on them. hkj-test writes them down, so your build can check them.

A red tower crane against a blue sky, its hook lowered

Read this page when your codebase has a container type of its own, and you want Functor, Monad, For and the rest to work with it. The worked example is Result: a value, or the reason there is none, of the kind many codebases write for themselves. If Either or an EitherPath would serve, use it instead, and skip this page.

What You'll Learn

  • Give a type of your own a witness, a helper and a Monad
  • Prove that the instance keeps its laws, with hkj-test
  • Pass the instance to code written for any container, such as For
  • Hold a type you cannot change, such as the JDK's Set, in a holder
  • Turn your type into a Path with GenericPath

See Example Code

The code on this page is in the owntype package: the page includes it, so the build compiles and runs it. OwnTypeBookTest.java runs the law tests and holds each claim the page makes.


What you write

PieceFor ResultWhat it does
A witness, inside a Kind interfaceResultKind.WitnessNames the container, so code generic over F can mention it
The type itselfResult, which extends ResultKindIs its own Kind, so widen allocates nothing
A helperResultKindHelper.RESULTMoves a Result into the encoding with widen, and back with narrow
An instanceResultMonad.INSTANCEGives of, map, ap and flatMap for Result

The pieces each type provides shows the same pieces for the library's own types. Most of those also have a token in Witnesses, for Instances to look up. Those tokens can only be built inside the library, so your code passes ResultMonad.INSTANCE wherever a Monad is asked for.

Your own type: Result

Result extends its own Kind interface, which declares the witness:

/** The Kind view of a {@link Result}: a Result whose container is named by {@link Witness}. */
public interface ResultKind<A> extends Kind<ResultKind.Witness, A> {

  /** Names the Result container. Nothing instantiates it; it appears only as a type argument. */
  final class Witness implements WitnessArity<TypeArity.Unary> {
    private Witness() {}
  }
}

Result itself is a sealed interface with two records:

public sealed interface Result<A> extends ResultKind<A> {

  record Ok<A>(A value) implements Result<A> {
    public Ok {
      Objects.requireNonNull(value, "value");
    }
  }

  record Failed<A>(String reason) implements Result<A> {
    public Failed {
      Objects.requireNonNull(reason, "reason");
    }
  }

  static <A> Result<A> ok(A value) {
    return new Ok<>(value);
  }

  static <A> Result<A> failed(String reason) {
    return new Failed<>(reason);
  }
}

A Result is a ResultKind, so it is already a Kind<ResultKind.Witness, A>. The helper's widen therefore returns its argument, and narrow needs only a type pattern:

public enum ResultKindHelper {
  RESULT;

  // A Result is already its own Kind, so widen returns the same object
  public <A> Kind<ResultKind.Witness, A> widen(Result<A> result) {
    return Objects.requireNonNull(result, "result");
  }

  public <A> Result<A> narrow(Kind<ResultKind.Witness, A> kind) {
    return switch (kind) {
      case null -> throw new KindUnwrapException("Cannot narrow a null Kind to a Result");
      case Result<A> result -> result;
      default -> throw new KindUnwrapException("Not a Result: " + kind.getClass().getName());
    };
  }
}

narrow throws KindUnwrapException for null, and for any other class that claims the witness, as the library's own helpers do. Type Arity explains the witness's WitnessArity<TypeArity.Unary> bound.

If your type carries its error type as a parameter, as a Result<E, A> would, the witness takes it too, as EitherKind.Witness<L> does. The instance then becomes a class with a generic instance() method, as EitherMonad has, since an enum cannot take a type parameter.

The instance

A Monad asks for four methods: of, map, ap and flatMap. map and flatMap narrow their argument and switch over the two records, of widens an Ok, and ap is built from flatMap and map:

public enum ResultMonad implements Monad<ResultKind.Witness> {
  INSTANCE;

  @Override
  public <A> Kind<ResultKind.Witness, A> of(A value) {
    return RESULT.widen(Result.ok(value));
  }

  @Override
  public <A, B> Kind<ResultKind.Witness, B> map(
      Function<? super A, ? extends B> f, Kind<ResultKind.Witness, A> fa) {
    return RESULT.widen(
        switch (RESULT.narrow(fa)) {
          case Result.Ok<A>(var value) -> Result.ok(f.apply(value));
          case Result.Failed<A>(var reason) -> Result.failed(reason);
        });
  }

  @Override
  public <A, B> Kind<ResultKind.Witness, B> flatMap(
      Function<? super A, ? extends Kind<ResultKind.Witness, B>> f,
      Kind<ResultKind.Witness, A> ma) {
    return switch (RESULT.narrow(ma)) {
      // narrow refuses a step that returned null, as the library's own instances do
      case Result.Ok<A>(var value) -> RESULT.widen(RESULT.narrow(f.apply(value)));
      case Result.Failed<A>(var reason) -> RESULT.widen(Result.failed(reason));
    };
  }

  @Override
  public <A, B> Kind<ResultKind.Witness, B> ap(
      Kind<ResultKind.Witness, ? extends Function<A, B>> ff, Kind<ResultKind.Witness, A> fa) {
    Objects.requireNonNull(fa, "fa");
    return flatMap(f -> map(f, fa), ff);
  }
}

A Failed passes through map and flatMap untouched, so a chain stops at its first failure, as an Either chain does. ap stops at the first failure too: when both arguments have failed, the function's reason wins. The instance holds no state, so one shared instance is enough, and a single-element enum gives you that.

The instance never builds or passes on null. Ok and Failed refuse it, so of(null) throws, and flatMap narrows what a step returns, so a step that returns null throws too. Values, never null gives the rule.

Prove your instance

No compiler checks how map and flatMap behave. A map that turned an Ok into a Failed would compile, and so would a flatMap that lost a Failed's reason. The laws say what callers rely on, and hkj-test's law checkers turn them into assertions:

  static Stream<Kind<ResultKind.Witness, Order>> results() {
    return Stream.of(
        RESULT.widen(Result.ok(ORDER)), RESULT.widen(Result.failed("order not found")));
  }

  @ParameterizedTest
  @MethodSource("results")
  @DisplayName("Result's helper and Monad keep their laws, on an Ok and on a Failed")
  void resultKeepsItsLaws(Kind<ResultKind.Witness, Order> fa) {
    Monad<ResultKind.Witness> monad = ResultMonad.INSTANCE;
    var same = KindEquivalence.<ResultKind.Witness>byEqualsAfter(RESULT::narrow);
    Function<Order, Kind<ResultKind.Witness, Customer>> findCustomer =
        order -> RESULT.widen(Result.ok(order.customer()));
    Function<Customer, Kind<ResultKind.Witness, EmailAddress>> verifyEmail =
        customer -> RESULT.widen(Result.failed("email not verified"));

    KindHelperLaws.assertRoundTrip(RESULT.narrow(fa), RESULT::widen, RESULT::narrow);
    FunctorLaws.assertIdentity(monad, fa, same);
    FunctorLaws.assertComposition(monad, fa, Order::customer, Customer::email, same);
    MonadLaws.assertLeftIdentity(monad, ORDER, findCustomer, same);
    MonadLaws.assertLeftIdentity(monad, ORDER.customer(), verifyEmail, same);
    MonadLaws.assertRightIdentity(monad, fa, same);
    MonadLaws.assertAssociativity(monad, fa, findCustomer, verifyEmail, same);
  }

  • KindHelperLaws.assertRoundTrip checks that narrow(widen(r)) is the very r you started with.
  • FunctorLaws checks identity, that mapping with x -> x changes nothing, and composition, that two maps equal one map of the composed function. Functor's laws states them.
  • MonadLaws checks left identity, right identity and associativity, as Monad's laws states them.
  • KindEquivalence.byEqualsAfter(RESULT::narrow) says when two Kinds count as the same: narrow both, then compare with equals, which a record already has.

Every law that takes a Result runs on an Ok and on a Failed, since each record has its own branch. verifyEmail always fails, so left identity is checked with a failing step too. ApplicativeLaws checks ap the same way, in the same test file. A law checker for MonadError is not supported yet.

The law checkers ship in hkj-test. ORDER is any Order, and the test uses these imports, with JUnit's:

import static org.higherkindedj.example.book.foundations.owntype.ResultKindHelper.RESULT;

import java.util.function.Function;
import java.util.stream.Stream;
import org.higherkindedj.example.book.foundations.owntype.Result;
import org.higherkindedj.example.book.foundations.owntype.ResultKind;
import org.higherkindedj.example.book.foundations.owntype.ResultMonad;
import org.higherkindedj.example.book.optics.cast.Customer;
import org.higherkindedj.example.book.optics.cast.EmailAddress;
import org.higherkindedj.example.book.optics.cast.Order;
import org.higherkindedj.hkt.Kind;
import org.higherkindedj.hkt.Monad;
import org.higherkindedj.hkt.assertions.KindEquivalence;
import org.higherkindedj.hkt.laws.FunctorLaws;
import org.higherkindedj.hkt.laws.KindHelperLaws;
import org.higherkindedj.hkt.laws.MonadLaws;

Use it with generic code

ResultMonad.INSTANCE is a Monad<ResultKind.Witness>, so code written for any container takes it. The chapter introduction's totals, and a For comprehension, both run on a Result:

    Result<BigDecimal> total =
        RESULT.narrow(totals(ResultMonad.INSTANCE, RESULT.widen(Result.ok(order))));
    // Ok[value=40.00]
    Result<String> receipt =
        RESULT.narrow(
            For.from(ResultMonad.INSTANCE, RESULT.widen(Result.ok(order)))
                .from(placed -> RESULT.widen(verified(placed.customer().email())))
                .yield((placed, email) -> "order " + placed.id() + " to " + email));
    // Ok[value=order 00000000-0000-0000-0000-000000000001 to ada@example.com]

Neither knows about Result; the instance does. A Failed order would give a Failed from both, with its reason.

A type you cannot change

The JDK's Set cannot extend your Kind interface, so the helper wraps it in a holder record that does:

public interface SetKind<A> extends Kind<SetKind.Witness, A> {

  final class Witness implements WitnessArity<TypeArity.Unary> {
    private Witness() {}
  }
}

public enum SetKindHelper {
  SET;

  // The holder is the Kind; the Set inside it is untouched
  private record SetHolder<A>(Set<A> set) implements SetKind<A> {
    SetHolder {
      Objects.requireNonNull(set, "set");
    }
  }

  public <A> Kind<SetKind.Witness, A> widen(Set<A> set) {
    return new SetHolder<>(set);
  }

  public <A> Set<A> narrow(Kind<SetKind.Witness, A> kind) {
    return switch (kind) {
      case null -> throw new KindUnwrapException("Cannot narrow a null Kind to a Set");
      case SetHolder<A>(var set) -> set;
      default -> throw new KindUnwrapException("Not a Set: " + kind.getClass().getName());
    };
  }
}

widen now allocates a holder, and narrow reads the Set back out with a record pattern. The round-trip law still holds, because narrow returns the very Set that went in. The holder shares that Set with the caller rather than copying it, so widen an unmodifiable one, such as Set.of or Set.copyOf gives. Lifting the Hood counts what a holder costs. Write an instance for Set as ResultMonad is written, through SET.narrow and SET.widen.

Your type gets a Path

Once the instance exists, GenericPath.of turns a Kind of your type into a Path. Application code can then use map and via, with no widen or narrow between the steps:

  // A Result as a Path, with Result's Monad behind it
  public static <A> GenericPath<ResultKind.Witness, A> path(Result<A> result) {
    return GenericPath.of(RESULT.widen(result), ResultMonad.INSTANCE);
  }

  // An email at example.com is verified; any other fails
  public static Result<String> verified(EmailAddress email) {
    return email.value().endsWith("@example.com")
        ? Result.ok(email.value())
        : Result.failed("email not verified");
  }

    Result<String> email =
        RESULT.narrow(
            path(Result.ok(order))
                .map(Order::customer)
                .via(customer -> path(verified(customer.email())))
                .runKind());
    // Ok[value=ada@example.com]
    Result<String> missing =
        RESULT.narrow(
            path(Result.<Order>failed("order not found"))
                .map(Order::customer)
                .via(customer -> path(verified(customer.email())))
                .runKind());
    // Failed[reason=order not found]

via takes a step that returns another Path, here built from the Result that verified returns. runKind hands back the Kind, and RESULT.narrow the Result. The Path's recover and recoverWith need a MonadError: built from a Monad alone, as here, they throw UnsupportedOperationException. Give GenericPath.of a MonadError instance, and they work. Generic Paths covers the rest. Recovery with errorType shows a MonadError for a type shaped like Result, and how @PathSource generates a named Path for it, with no runKind or narrow.


Previous: Lifting the Hood Next: Type Classes