Skip to content

jeziellago/ktxsafe

Repository files navigation

KtxSafe

Kotlin functions and extensions to do safe unwrap and extract values.

Add dependencies

  • Project build.gradle
allprojects {
    repositories {
		...
		maven { url 'https://jitpack.io' }
	}
}
  • Module build.gradle
dependencies {
	implementation 'com.github.jeziellago:ktxsafe:VERSION'
}

Nullable values

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
}

Handle null conditions with orElse:

whenNotNull(nA, nB, nC) { a, b, c -> 
    // execute only `nA`, `nB` and `nC` are not null
}.orElse {
   // do something if any is null
}

List of nullable values:

withAllNotNull(a, b, c, d, e...n) { 
    ...
}

or

whenAllNotNull(a, b, c, d, e,...n) { 
    ...
}.orElse {
    ...
}

With single values:

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
}

Extract values safely

Extract value or throw

anyNullableValue.getOrThrow(Exception("Must be non-null"))

Extract value or default

anyNullableValue.getOrDefault(defaultValue)

Extract value or else

anyNullableValue.getOrElse { "return this value as default" }

Safe try block

val result = tryOrNull { doSomething() }

or

val result = tryOrNull({ /* log exception */ }, { doSomething() })

About

Kotlin functions and extensions to do safe unwrap and extract values.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages