Skip to content

Instantly share code, notes, and snippets.

@DHosseiny
Last active November 6, 2018 07:16
Show Gist options
  • Save DHosseiny/8d928ba51ba02c17f31d912ae9593065 to your computer and use it in GitHub Desktop.
Save DHosseiny/8d928ba51ba02c17f31d912ae9593065 to your computer and use it in GitHub Desktop.
Optional for android api lower than 24.
class Optional<T> {
private var value: T? = null
private constructor() {
this.value = null
}
private constructor(value: T) {
this.value = value
}
fun ifPresent(action: (T) -> Unit) {
if (value != null) {
action(value!!)
}
}
fun ifPresentOrElse(action: (T) -> Unit, orElse: () -> Unit) {
if (value != null) {
action(value!!)
} else orElse()
}
fun isPresent() = value != null
fun get() = value!!
companion object {
@JvmStatic
fun <T> empty(): Optional<T> {
return Optional()
}
@JvmStatic
fun <T> of(value: T): Optional<T> {
return Optional(value)
}
}
}
@DHosseiny
Copy link
Author

Contribute and add other Java optional methods.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment