Skip to content

Instantly share code, notes, and snippets.

@raxityo
Last active February 11, 2019 18:52
Show Gist options
  • Save raxityo/8a109787966abc38c27b5620ce93b225 to your computer and use it in GitHub Desktop.
Save raxityo/8a109787966abc38c27b5620ce93b225 to your computer and use it in GitHub Desktop.
A Kotlin extension to introduce optional chaining to error handling.
inline fun <T> tryOptional(expression: () -> T): T? {
return try {
expression()
} catch (ex: Throwable) {
null
}
}
@raxityo
Copy link
Author

raxityo commented Feb 11, 2019

Usage:

tryOptional {

    // Expression that may throw an exception or return a value
    giveMeSomething()

}?.let { something ->

    // Something is guaranteed to be available here
   	print("I have something: $something")

} ?: print("I have nothing")

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