September 2023
Intermediate to advanced
470 pages
11h 12m
English
We started our search for a kind of “magic arrow”; functors can work exactly in this way—as you may have already guessed.
To see how this would work, let’s look again at the transform method of Holder; it’s very simple, but we can add a condition: do the transformation only if the value isn’t an error. We can define a class like this:
| | data class ConstantOrErrorF<T>( val value:T?, val isError: Boolean) { |
| | |
| | fun <U> transform(f: (T) -> U): ConstantOrErrorF<U> = |
| | if (isError || value == null) |
| | ConstantOrErrorF(null, true) |
| | else |
| | ConstantOrErrorF(f(value), false) |
| | } |
This would work, but we can do better than this.
Instead of using a boolean to represent ...
Read now
Unlock full access