Working with Kind: Widen, Call, Narrow
Five steps take a value into Kind<F, A>, through a type class, and back out.

- Pick the witness for a container, and ask
Instancesfor its type class - Widen a value, call the type class on it, and narrow the result
- Write one method over
MonadErrorthat runs unchanged on aMaybeand anEither - Recover from a failure inside the encoding, in code written for any container
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
- Pick the witness. It names the container in your types:
MaybeKind.WitnessforMaybe,EitherKind.Witness<L>for anEitherwhose left type isL,ListKind.WitnessforList, andOptionalKind.WitnessforOptional. Every other type follows the pattern, such asTryKind.WitnessforTry. - Ask
Instancesfor the type class.Instances.monadError(maybe())givesMaybe'sMonadError, wheremaybe()names the witness. Obtaining Instances covers every lookup. - Widen the value with its type's helper, such as
MAYBE.widen(...). - Call a method on the instance, passing the
Kind:map,flatMap,raiseErrororhandleErrorWith. AKindhas no methods of its own. - 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'stotalsneeded only aFunctor, since nothing there could fail. AMonadErroris aMonadthat can also raise an error and recover from one. - The bound on
Fsays it names a container with one type argument missing. TheWitnessAritybound explains it. ofandraiseErrorcome from the instance, so the method builds results without knowing the container.flatMapruns its function only when there is an order. On aNothing, the function never runs, and theNothingcomes back.- The caller passes the error. The method knows nothing about
E, so it cannot build one: the caller passesUnit.INSTANCEforMaybe, and a message for anEitherwhose left type isString.
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)
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 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.
This compiles. What happens when it runs?
MonadError<OptionalKind.Witness, String> me = Instances.monadError(optional());
me.raiseError("out of stock");
Answer and why
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.
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
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
narrowthrowsKindUnwrapExceptionfor anull, or for another container'sKind. It is a bug to fix, not a failure to recover. See Whennarrowthrows.- Widening a JDK type allocates a holder. Widening
OptionalorListallocates one, and wideningMaybeorEitherdoes not. See The pieces each type provides.
Previous: How the Encoding Works Next: Obtaining Instances