Giter Site home page Giter Site logo

kotlin-options's Introduction

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.

Usage:

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:

    getCurrentUserId()
            .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:

    Observable.just(optionOf("abc"))
        .filterNotNone()
        .subscribe { println(it.length) } // use String value

Test Assertions

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

    val someOption = optionOf("abc") 
    assertThat(someOption).hasValue("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.

Download

Available on Jitpack.

Alternatives

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.

Acknowledgements

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

Chilicorn Logo

License

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

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

kotlin-options's People

Contributors

peter-tackage avatar tomaszpolanski avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

kotlin-options's Issues

Mocking framework

Hi,

hope find you well with this cold call.

I am an author of mocking framework for Kotlin

I see you are using mockito-kotlin.

I just want you to be aware that there is solution that fully supports Kotlin and ask to try it in your new/current projects.

I can help you if you answer to this issue.

Thanks and please star it

Updating readme with kotlin's version of mapping

How about showing in README first how kotlin would do it's null mapping, something like this:

getCurrentUserId()
    ?.takeIf { it.isNotEmpty() && it != "Invalid Id" }
    ?.let { getCurrentUserFromDatabase(it) }
    ?.username
    ?.let { "Logged in user: $it" }
    .apply {
        if (this != null) {
            log(this)
        } else {
            log("No user to login!")
        }
    }

Of course we would need to mentione that those versions of getCurrentUserId and getCurrentUserFromDatabase return kotlin's nullable

Make Some constructor visible

Currently the constructor for Some is marked internal. I am now thinking that there's no benefit to not exposing it and preventing direct instantiation as:

  1. We already expose the Some and None classes, so these types are known by library clients.
  2. By ensuring the Some constructor only takes <T : Any> we prevent incorrect creation or require checkNotNull like in Java - there's no run time risk.
  3. For readability purposes, it would make defining a specific Option value clearer when using non-nulls than requiring use of optionOf. It could just be Some("abc").

Thoughts? @tomaszpolanski

filterIfSome vs filterNotNone

In kotlin method for filtering out nulls from a list is called filterNotNull.
Would it make sense to add filterNotNone and deprecate the filterIfSome?

Allow independent distribution of modules via Bintray

The distribution of the artifacts generated from the modules needs to be modified so that each module can be independent included by using a separate artifactId. After this Investigation should include how to upload bintray rather than jitpack.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.