okuzawatsの日記

Android / Kotlin Enthusiast 🤖

Either / Option in Kotlin

In some functional languages, such as Scala, Either and Option is provided. Either represents what type of exception a function may throws and what type of value the function returns in success cases. Option represents absence of a value instead of nullable.

Either / Option in Kotlin

Since Kotlin do not provide Either or Option (at least for version 1.5), we have to use third-patry library to introduce Either or Option. The most realistic option at this moment is using Arrow. Arrow is “Functional companion to Kotlin’s Standard Library”.

I also re-implemented Either and Option in Kotlin. The code is published as a library so you can use it. It’s completely a hobby project, so be care to use it in production :)

Either

Either has subtypes of Left and Right. Left represents an exception. Right represents success cases and has a value. It goes something like this.

sealed class Either<out E : Throwable, out T : Any> {
  data class Left<out E : Throwable>(val error: E) : Either<E, Nothing>()
  data class Right<out T : Any>(val value: T) : Either<Nothing, T>()
}

For example, if a function returns a value or throws an exception, the returned value could be lifted to Either. Requesting via Web API is the typical case.

suspend fun getAwesomeValue(): Either<AwesomeException, AwesomeValue> {
  val response = apiClient.getAwesomeResponse()
  return if (response.isSuccessful) {
    Either.Right(value = requireNotNull(response.body()))
  } else {
    Either.Left(error = AwesomeException())
  }
}

On the side receiving the Either, when could be used instead of pattern matching since Kotlin does not provide pattern matching (at least for version 1.5).

when (it) {
  is Either.Left -> {
    // do something here
  }
  is Either.Right -> {
    // do something here
  }
}

Option

Option has subtypes of Some and None. Some represents that Option has a value. None represents that Option does not have any value.

sealed class Option<out T : Any> {
  data class Some<out T : Any>(val value: T) : Option<T>()
  object None : Option<Nothing>()
}

Nullable could be replaced with Option. Like Either, when could be used for Option value also.

References

#Kotlin

About me 😎

profile

茨城県つくば市在住のソフトウェアエンジニアです。専門領域はAndroidアプリ開発で、特にアーキテクチャに興味があります。某社でAndroidアプリ開発のテックリードをしています。

Jetpack ComposeによるAndroid MVVMアーキテクチャ入門の著者です。

👉 もっと詳しく

Writing 📝

Android MVVMアーキテクチャ入門

Androidアプリ開発の初学者に向けた、MVVM(Model-View-ViewModel)アーキテクチャの入門書を書きました。初学者の方を確実にネクストレベルに引き上げる技術書です。

👉 もっと詳しく

See Also 👀