July 2018
Intermediate to advanced
242 pages
8h 6m
English
One of the essential functional programming features the Either Monad can provide, is the ability to apply functions to its values. We can simply extend the Either class with the fold() function, which can take two functions as the parameters. The first function that should be applied to the Either.Left type and second, that should be applied to Either.Right:
sealed class Either<out L, out R> { data class Left<out L>(val left: L) : Either<L, Nothing>() data class Right<out R>(val right: R) : Either<Nothing, R>() fun <T> fold(leftOp: (L) -> T, rightOp: (R) -> T): T = when (this) { is Left -> leftOp(this.left) is Right -> rightOp(this.right) } //...}
The fold() function is going to return a value from either the leftOp or
Read now
Unlock full access