Working with Kind: Widen, Call, Narrow

Five steps take a value into Kind<F, A>, through a type class, and back out.

A man in a glass-walled room holds his hands together in a diamond shape in front of him

What You'll Learn

  • Pick the witness for a container, and ask Instances for its type class
  • Widen a value, call the type class on it, and narrow the result
  • Write one method over MonadError that runs unchanged on a Maybe and an Either
  • Recover from a failure inside the encoding, in code written for any container

See Example Code

The code on this page is WorkingWithKindBook.java: the page includes it, so the build compiles and runs it. WorkingWithKindBookTest.java holds each claim the page makes.


This page is for code written once for any container. Code for one container, such as a service method that returns an EitherPath, stays with Effect Paths, and the Foundations introduction's "Which level am I working at?" tip says how to tell which you need.

The five steps

  1. Pick the witness. It names the container in your types: MaybeKind.Witness for Maybe, EitherKind.Witness<L> for an Either whose left type is L, ListKind.Witness for List, and OptionalKind.Witness for Optional. Every other type follows the pattern, such as TryKind.Witness for Try.
  2. Ask Instances for the type class. Instances.monadError(maybe()) gives Maybe's MonadError, where maybe() names the witness. Obtaining Instances covers every lookup.
  3. Widen the value with its type's helper, such as MAYBE.widen(...).
  4. Call a method on the instance, passing the Kind: map, flatMap, raiseError or handleErrorWith. A Kind has no methods of its own.
  5. Narrow the result with the same helper, such as MAYBE.narrow(...).

The code on this page uses these imports, with Order and OrderStatus from the order records the Optics chapter introduces:

import static org.higherkindedj.hkt.either.EitherKindHelper.EITHER;
import static org.higherkindedj.hkt.instances.Witnesses.either;
import static org.higherkindedj.hkt.instances.Witnesses.maybe;
import static org.higherkindedj.hkt.instances.Witnesses.optional;
import static org.higherkindedj.hkt.maybe.MaybeKindHelper.MAYBE;

import java.math.BigDecimal;
import org.higherkindedj.example.book.optics.cast.Order;
import org.higherkindedj.example.book.optics.cast.OrderStatus;
import org.higherkindedj.hkt.Kind;
import org.higherkindedj.hkt.MonadError;
import org.higherkindedj.hkt.TypeArity;
import org.higherkindedj.hkt.Unit;
import org.higherkindedj.hkt.WitnessArity;
import org.higherkindedj.hkt.either.Either;
import org.higherkindedj.hkt.either.EitherKind;
import org.higherkindedj.hkt.instances.Instances;
import org.higherkindedj.hkt.maybe.Maybe;
import org.higherkindedj.hkt.maybe.MaybeKind;
import org.higherkindedj.hkt.optional.OptionalKind;

Write the method once

totalUnlessShipped totals an order, and refuses one that has already shipped. It never names Maybe: it is written over a MonadError for any F.

  // One method for any container F that can hold a failure of type E
  static <F extends WitnessArity<TypeArity.Unary>, E> Kind<F, BigDecimal> totalUnlessShipped(
      MonadError<F, E> monadError, Kind<F, Order> order, E refusal) {
    return monadError.flatMap(
        o ->
            o.status() == OrderStatus.SHIPPED
                ? monadError.raiseError(refusal)
                : monadError.of(total(o)),
        order);
  }

  • It asks for a MonadError, because refusing an order is a failure. The introduction's totals needed only a Functor, since nothing there could fail. A MonadError is a Monad that can also raise an error and recover from one.
  • The bound on F says it names a container with one type argument missing. The WitnessArity bound explains it.
  • of and raiseError come from the instance, so the method builds results without knowing the container.
  • flatMap runs its function only when there is an order. On a Nothing, the function never runs, and the Nothing comes back.
  • The caller passes the error. The method knows nothing about E, so it cannot build one: the caller passes Unit.INSTANCE for Maybe, and a message for an Either whose left type is String.

Take it through the steps

Here the five steps total an order held in a Maybe:

    // steps 1 and 2: Maybe's witness, named by maybe(), and the instance for it
    MonadError<MaybeKind.Witness, Unit> maybeErrors = Instances.monadError(maybe());

    // step 3, widen: the Maybe, seen as a Kind
    Kind<MaybeKind.Witness, Order> found = MAYBE.widen(Maybe.just(placed));

    // step 4, call: the method sees only the Kind and the instance
    Kind<MaybeKind.Witness, BigDecimal> totalKind =
        totalUnlessShipped(maybeErrors, found, Unit.INSTANCE);

    // step 5, narrow: back to a Maybe
    Maybe<BigDecimal> maybeTotal = MAYBE.narrow(totalKind);
    // Just(50.00)

The same method runs unchanged on an Either:

    // the same method, unchanged, with Either's instance and a message as the error
    MonadError<EitherKind.Witness<String>, String> eitherErrors = Instances.monadError(either());

    Either<String, BigDecimal> refused =
        EITHER.narrow(
            totalUnlessShipped(
                eitherErrors, EITHER.widen(Either.right(shipped)), "order already shipped"));
    // Left(order already shipped)

The compiler does not check E

Instances.monadError takes E from the variable you assign it to, and nothing checks it against the instance. MonadError<MaybeKind.Witness, String> compiles, then throws ClassCastException when you raise a String. Declare the error type the instance has, Unit for Maybe, from the table in Obtaining Instances.

Recover in code for any container

Code written for any F cannot narrow, because it does not know which helper to use. So it recovers through the instance: handleErrorWith takes the failed Kind and a function from the error to a replacement.

  // Generic code cannot narrow, so it recovers through the instance
  static <F extends WitnessArity<TypeArity.Unary>, E> Kind<F, BigDecimal> totalOrZero(
      MonadError<F, E> monadError, Kind<F, Order> order, E refusal) {
    return monadError.handleErrorWith(
        totalUnlessShipped(monadError, order, refusal), _ -> monadError.of(BigDecimal.ZERO));
  }

    // a shipped order, recovered to zero before narrowing
    Maybe<BigDecimal> orZero =
        MAYBE.narrow(totalOrZero(maybeErrors, MAYBE.widen(Maybe.just(shipped)), Unit.INSTANCE));
    // Just(0)

For a chain of several dependent steps, a for comprehension reads more easily than nested flatMap calls.

You can ship now

You can now write one method over a type class and run it on any container that has an instance: widen, call, narrow. The rest of this page is for when narrow throws, and what widening allocates.

Checkpoint: an error type the instance does not have

This compiles. What happens when it runs?

MonadError<OptionalKind.Witness, String> me = Instances.monadError(optional());
me.raiseError("out of stock");

Answer and why

raiseError throws ClassCastException. Instances.monadError takes E from the variable, and nothing checks it against the instance: Optional's error type is Unit, not String. Declare MonadError<OptionalKind.Witness, Unit>, and raise Unit.INSTANCE.

Where this lives: Take it through the steps, with each type's error type in Obtaining Instances.

Checkpoint: narrowing inside a generic method

A method written for any F gets back a Kind<F, BigDecimal>. Can it narrow that with MAYBE.narrow to give zero when the total failed? If not, how does it give zero?

<F extends WitnessArity<TypeArity.Unary>> BigDecimal peekAtTotal(Kind<F, BigDecimal> total) {
    return MAYBE.narrow(total).orElse(BigDecimal.ZERO);
}

Answer and why

No: javac refuses it, because Kind<F, BigDecimal> "cannot be converted to" Maybe's Kind. The method does not know that F is Maybe, so it cannot pick a helper, and it cannot return a plain BigDecimal either. It takes the MonadError for F, returns a Kind<F, BigDecimal> and recovers through the instance, as totalOrZero does with handleErrorWith. The caller, who knows F, narrows.

Where this lives: Recover in code for any container.


The fine print

  • narrow throws KindUnwrapException for a null, or for another container's Kind. It is a bug to fix, not a failure to recover. See When narrow throws.
  • Widening a JDK type allocates a holder. Widening Optional or List allocates one, and widening Maybe or Either does not. See The pieces each type provides.

Previous: How the Encoding Works Next: Obtaining Instances