Functional Error Management in Kotlin: An Introduction to Arrow-Kt Either Data Type

Arrow.Kt is a functional programming library for Kotlin that provides a powerful set of abstractions for working with functional data types. One of these abstractions is the Either data type, which is a way to represent values that can be one of two possible types.

Either Data Type, if Left means exception and right for result
Either<Exception,Result> Left is for exception and result always right
sealed class Either<out L, out R> {
data class Left<out L>(val value: L) : Either<L, Nothing>()
data class Right<out R>(val value: R) : Either<Nothing, R>()
}
dependencies {
implementation "io.arrow-kt:arrow-core:$arrow_version"
}
// Step 1: Define a function that returns an Either
fun getDataFromServer(url: String): Either<IOException, String> {
return try {
val response = URL(url).readText()
Either.Right(response)
} catch (e: IOException) {
Either.Left(e)
}
}

// Step 2: Call the function and store the result in a variable
val result = getDataFromServer("https://example.com")
// result is of type Either<IOException, String>

// Step 3: Use the map function to transform the result
val processedData = result.map { it.split(",") }
// processedData is of type Either<IOException, List<String>>

// Step 4: Use the fold function to handle the success and failure cases
val finalResult = processedData.fold(
{ "Error: ${it.message}" },
{ "Data: $it" }
)
// finalResult is of type String
val result = getDataFromServer("https://example.com")

when(result) {
is Either.Left -> println("Error: ${result.a}")
is Either.Right -> println("Data: ${result.b}")
}
fun validateForm(form: Form): Either<String, Form> {
val usernameError = validateUsername(form.username)
if (usernameError != null)
return Either.Left(usernameError)

val emailError = validateEmail(form.email)
if (emailError != null)
return Either.Left(emailError)

val passwordError = validatePassword(form.password)
if (passwordError != null)
return Either.Left(passwordError)
return Either.Right(form)
}

Appreciate the read? Give it a clap, hit that follow button, leave a comment, Let’s grow together.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Anand Verma

Android enthusiastic, currently Associate Director Of Engineering @SunstoneEduversity