Disclaimer:
We don't think that Kotlin itself needs
Optionalbecause it has strong null-safe type system that effectively eliminates need in such a wrapper. However there are APIs and libraries like RxJava 2 which don't acceptnullvalues.
We also think that in many cases you can use
sealed classes to express absent values, however in simple cases like passingString?through Rx streamOptionalis a more convenient solution.
The goal of this implementation is to be convenient to use and fit Kotlin's null-safe type system, which resulted in:
- Only two functions (mimics Kotlin std
toInt()/toBoolean()/etc):fun <T : Any> T?.toOptional(): Optional<T>fun Optional.toNullable(): T?
SomeandNoneare declared as top level types — no need to writeOptional.SomeorOptional.None- No functions like
map(),getOrElse(),filter(), etc — applytoNullable()and use Kotlin sdt functions likelet(),takeIf()and so on.
val some = Some(value)val none = None // It's an object!// If something is null — you'll get None, otherwise you'll get Some(something).
val o = something.toOptional()// If Optional is None — you'll get null, otherwise you'll get not null T value.
val t = optional.toNullable()val f = optional.toNullable() ?: "fallback"when (optional) {
is Some -> {}
is None -> {}
}val values: Observable<String> = Observable
.just(Some("a"), None, Some("b"))
.filterSome()
.map { value: String -> } // filterSome() unwraps value for you.val noneSignals: Observable<Unit> = Observable
.just(Some("a"), None, Some("b"))
.filterNone()
.map { none: Unit -> } // filterNone() maps None to Unit.Koptional is available on jcenter.
Optional type:
compile 'com.gojuno.koptional:koptional:put-some-version'RxJava 2 extensions:
compile 'com.gojuno.koptional:koptional-rxjava2-extensions:put-some-version'All the releases and changelogs can be found on Releases Page.
Dependencies: you only need docker and bash installed on your machine.
bash ci/build.shCopyright 2017 Juno, Inc.
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.