Not the Optional Kotlin wanted, but the Optional it deserves.. 😩
🍻 Tastes Great with RxJava!™
This is a very simple implementation of an Optional class, like the one in Arrow or Guava.
Koptional is written in Kotlin, so the Kotlin compiler doesn't have to interpret the nullability of values, and sometimes fails.
Optional.of(maybeInt) // Returns Optional<Int?> in Arrow/Guava 😧
Koptional lets Kotlin's nullability features shine by directly allowing you read access to the value of the optional, you can continue to use kotlin's features for null checks directly
val optional = Optional(maybeInt)
val withDefault = optional.value ?: 50
If you haven't already, add JitPack to your gradle repositories. This sweet baby boy 👶 will give you access to install our libraries.
repositories {
maven {
url "https://jitpack.io"
}
}
Then just add it as a dependency to your module!
compile 'com.github.InkApplications:Koptional:1.0.0'
Using Koptional is easy 🍰
Koptional just uses a standard class constructor. 👷
val optional = Optional(maybeInt) // Gives an Optional<Int>
Koptional is just a dumb wrapper. 😵 Values can be accessed and tested through properties:
val optional = Optional(maybeInt)
if (optional.isPresent) {
printLn("Check that value: ${optional.value}")
}
If you wanna go deeper ⌚ into Kotlin world, we've got some inline methods you can use for checking values more declaratively 📢
val optional = Optional(maybeInt)
optional.whenPresent {
printLn("Check that value $it")
} whenAbsent {
printLn("There's no number!! 😡")
}
// or just
optional.whenAbsent {
printLn("Pary while the numbers are away! 🎉")
}
Koptional doesn't have a method for .or(T)
like others.
That's because doing this in Kotlin is easy by itself 👌😩
val optional = Optional(maybeInt)
val withDefault = optional.value ?: 50
printLn("This value always exists ➡ $withDefault")
Kotlin's pretty dope 🤑 – If you've got more methods to make this even simpler or more useful then just make a PR. Keep it Simple. ✌