Functional Option that can be used with Java 1.6 and Android.
Similar to Java 8 Optional
but targeting Android and Java 6.
In 1965, Sir Tony Hoare introduced null
reference. Since then he apologised for that and called it The Billion Dollar Mistake.
If the inventor of null
pointers and references has condemned them, why the rest of us should be using them?
Currently there are several ways to say that an object could be null. Most popular way in Android nowadays is using Nullable
or NonNull
annotations.
The problem with those annotations is that you cannot say what kind of objects are in an array, or if you use Rx, in an Observable
.
With Options
you can use instead List<Option<String>>
or in Rx Observable<Option<Integer>>
.
If you have been using RxJava, this API will look really similar to RxJava.
Still Option
is synchronous API that does not have too much to do with Reactive Programming.
Basic usage
Code with nulls
:
String input = ...;
String result = null;
if (input != null && input.length() > 0) {
result = "Length of the string is " + input.length();
} else {
result = "The string is null or empty";
}
Code with Options
:
String input = ...;
String result = Option.ofObj(input)
.filter(str -> str.length() > 0)
.match(str -> "Length of the string is " + str.length(),
() -> "The string is null or empty");
Advance usage
Code with nulls
:
String input = ...;
String result = null;
if (input != null) {
try {
int intValue = Integer.parseInt(input);
result = "Input can be parsed to number: " + intValue;
} catch (NumberFormatException e) {
result = "Input is not a number";
}
}
Code with Options
:
String input = ...;
String result = Option.ofObj(input)
.flatMap(str -> Option.tryAsOption(() -> Integer.parseInt(str)))
.map(intValue -> "Input can be parsed to number: " + intValue)
.orDefault(() -> "Input is not a number");
Options are available on maven via jitpack. Just add to your gradle files:
To your top level gradle.build file add repository:
repositories {
jcenter()
maven { url "https://jitpack.io" }
}
To your module level gradle.build add dependency:
dependencies {
// other dependencies
implementation 'com.github.tomaszpolanski:options:1.3.0'
}
Sure, you can, but I would recommend using Peter Tackage's kotlin-options as they play nicer with Kotlin.
This library was strongly influenced by C# Functional Language Extensions.