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:
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!") })
Extension methods are provided to transform to transform Iterable
s.
val optionListWithNone : List<Option<String>> = listOf(optionOf("abc"), None)
val listWithout : List<String> = listWithNone.filterNotNone() // `None` elements removed
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
You can test your Options using the kotlin-options-assertions module.
val someOption = optionOf("abc")
assertThat(someOption).hasValue("abc")
The kotlin-options-moshi-adapter module provides serialization between JSON and Option
using Moshi.
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.
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.