Kotlin functions and extensions to do safe unwrap and extract values.
- Project
build.gradle
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
- Module
build.gradle
dependencies {
implementation 'com.github.jeziellago:ktxsafe:VERSION'
}
Handle multiples nullable values on conditions is hard and decrease readability in binary conditions.
KtxSafe improve readability:
val nA: String? = ...
val nB: Boolean? = ...
val nC: Int? = ...
withNotNull(nA, nB, nC) { a, b, c ->
// execute only `nA`, `nB` and `nC` are not null
}
whenNotNull(nA, nB, nC) { a, b, c ->
// execute only `nA`, `nB` and `nC` are not null
}.orElse {
// do something if any is null
}
withAllNotNull(a, b, c, d, e...n) {
...
}
or
whenAllNotNull(a, b, c, d, e,...n) {
...
}.orElse {
...
}
val value: Any? = ...
withNotNull(value) {
// do something if `value` is not null
}
or
val value: Any? = ...
value.whenNotNull {
// do something if `value` is not null
}.orElse {
// do something if `value` is null
}
anyNullableValue.getOrThrow(Exception("Must be non-null"))
anyNullableValue.getOrDefault(defaultValue)
anyNullableValue.getOrElse { "return this value as default" }
val result = tryOrNull { doSomething() }
or
val result = tryOrNull({ /* log exception */ }, { doSomething() })