Awesome Open Source
Awesome Open Source

Kotlin Functional Options

Build Status Release

Options in Kotlin using sealed classes.

Kotlin has nullable types, however, the use of null as a value is not supported in some popular libraries, such as RxJava 2. This means that another way of representing the absence of a value is required.

This mini-library allows you to safely represent the absence of a value without nulls and provides functional operators to transform the value.


Create an Option from a nullable type using optionOf:

    fun getCurrentUserId() : Option<String> {
        val userId : String? = getUserId() // something which might return null
        return optionOf(value)

Transform the value by chaining functional operators as required:

            .filter { it.isNotEmpty() && it != "Invalid Id" }
            .flatMap { getCurrentUserFromDatabase(it) }
            .map { it.username }
            .map { "Logged in user: $it" }
            .matchAction( { log(it) }, { log("No user to login!") })

Iterable Extensions

Extension methods are provided to transform to transform Iterables.

    val optionListWithNone : List<Option<String>> = listOf(optionOf("abc"), None) 
    val listWithout : List<String> = listWithNone.filterNotNone() // `None` elements removed

Extra Modules

RxJava 2 Extensions

Extension methods are also provided to transform RxJava 2 streams, including Observable, Flowable, Single and Maybe using kotlin-options-rxjava2-extensions.

You can use this to filter an Option to its value:

        .subscribe { println(it.length) } // use String value

Test Assertions

You can test your Options using the kotlin-options-assertions module.

    val someOption = optionOf("abc") 

Moshi Adapter

The kotlin-options-moshi-adapter module provides serialization between JSON and Option using Moshi.

Retrofit Converter

The kotlin-options-moshi-adapter module provides Retrofit 2 calls which return Option.


Available on Jitpack.


The API of this library was inspired by the Java 6 compatible Options library written by Tomek Polanski.

If you want an Optional without much of the functional behaviour, check out Koptional.


Brought to you by the power of the Chilicorn and the Futurice Open Source Program.

Chilicorn Logo


Copyright 2017 Peter Tackage

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
See the License for the specific language governing permissions and
limitations under the License.

Get A Weekly Email With Trending Projects For These Topics
No Spam. Unsubscribe easily at any time.
kotlin (3,570
rxjava2 (219
functional (148
retrofit (95
options (36