Android – How To Implement Either Monad Design Pattern in Kotlin ?

Hello Readers, CoolMonkTechie heartily welcomes you in this article (How To Implement Either Monad Design Pattern in Kotlin ?).

In this article, we will learn about how to implement Either Monad Design Pattern in Kotlin. The concept of Monad is one of the fundamental functional programming design patterns. We can understand a Monad as an encapsulation for a data type that adds a specific functionality to it or provides custom handlers for different states of the encapsulated object.

One of the most commonly used is a Maybe monad. The Maybe monad is supposed to provide information about the enclosed property presence. It can return an instance of the wrapped type whenever it’s available or nothing when it’s not. Java 8 introduced the Optional class, which is implementing the Maybe concept. It’s a great way to avoid operating on null values. This article explains about Either Monad Design Pattern work flows in Kotlin.

To understand the Either Monad Design Pattern in Kotlin, we cover the below topics as below :

  • Overview
  • Pattern Implementation Steps
  • How Pattern Works ?

A famous quote about learning is :

” The beautiful thing about learning is that nobody can take it away from you.”

So Let’s begin.

Overview

We can understand about Either Monad Design Pattern as:

  • A fundamental functional programming design patterns and,
  • Consider a Monad as an encapsulation for a data type that adds a specific functionality or provides custom handlers for different states of the encapsulated object.

However, apart from having the information about the unavailable state, we would often like to be able to provide some additional information. For example, if the server returns an empty response, it would be useful to get an error code or a message instead of the null or an empty response string. This is a scenario for another type of Monad, usually called Either, which we are going to implement in this article.

Pattern Implementation Steps

In this section, We will understand how to implement it and What steps are required for implementation.

Step 1 – Declare Either as a sealed class

sealed class Either<out E, out V>

Step 2 – Add two subclasses of Either, representing Error and Value:

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>()
 }
 

Step 3 – Add factory functions to conveniently instantiate Either:

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>()

     companion object {
        fun <R> right(value: R): Either<Nothing, R> = Either.Right(value) 
        fun <L> left(value: L): Either<L, Nothing> = Either.Left(value)
     }
 }

How Pattern Works ?

In order to make use of the class Either and benefit from the Either.right() and Either.left() methods, we can implement a getEither() function that will try to perform some operation passed to it as a parameter. If the operation succeeds, it is going to return the Either.Right instance holding the result of the operation, otherwise, it is going to return Either.Left, holding a thrown exception instance:

fun<V> getEither(action: () -> V): Either<Exception, V> =
         try { Either.right(action()) } catch (e: Exception) { Either.left(e) }
 

By convention, we can use the Either.Right type to provide a default value and Either.Left to handle any possible edge cases.

One essential functional programming feature 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 should be applied to the Either.Left type and the second 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 will return a value from either the leftOp or rightOp function, whichever is used. The usage of the fold() function can be illustrated with a server-request parsing example.

Suppose we have the following types declared:

data class Response(val json: JsonObject)
data class ErrorResponse(val code: Int, val message: String)

And we have also a function responsible for delivering a backend response:

fun someGetRequest(): Either<ErrorResponse, Response> = //..
  

We can use the fold() function to handle the returned value in the right way:

someGetRequest().fold({
     showErrorInfo(it.message)
 }, {
     parseAndDisplayResults(it.json)
 })

We can also extend the Either class with other useful functions, like the ones available in the standard library for data-processing operations—mapfilter, and exists.

That’s all about in this article.

Related Other Articles / Posts

Conclusion

In this article, we understood about how to implement Either Monad Design Pattern in Kotlin. This article explained about Either Monad Design Pattern work flows in Kotlin.

Thanks for reading! I hope you enjoyed and learned about Either Monad Design Pattern concepts in Kotlin. Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe to the blog and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

You can find other articles of CoolMonkTechie as below link :

You can also follow official website and tutorials of Android as below links :

If you have any comments, questions, or think I missed something, leave them below in the comment box.

Thanks again Reading. HAPPY READING !!???

Loading

Summary
Android - How To Implement Either Monad Design Pattern in Kotlin ?
Article Name
Android - How To Implement Either Monad Design Pattern in Kotlin ?
Description
This article explains about Either Monad Design Pattern work flows in Kotlin. This is a great way to avoid operating on null values.
Author

1 thought on “Android – How To Implement Either Monad Design Pattern in Kotlin ?”

Leave a Comment