Last active
November 6, 2018 07:16
-
-
Save DHosseiny/8d928ba51ba02c17f31d912ae9593065 to your computer and use it in GitHub Desktop.
Optional for android api lower than 24.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Contribute and add other Java optional methods.